diff --git a/.github/workflows/format-java.yml b/.github/workflows/format-java.yml new file mode 100644 index 00000000..3b15c202 --- /dev/null +++ b/.github/workflows/format-java.yml @@ -0,0 +1,47 @@ +# Runs formatting requirements +name: Java Formatting + +on: + push: + branches: ['1.20.1', '1.21.1'] + paths: ['src/main/java/**', 'src/test/**'] + pull_request: + paths: ['**'] + +concurrency: + group: formatting-${{ github.ref }} + cancel-in-progress: true + +jobs: + formatting: + name: Formatting + runs-on: ubuntu-latest + permissions: + pull-requests: read + steps: + - name: Checkout Repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 # do a full checkout instead of a shallow clone of HEAD so spotless's ratchetFrom works + - name: Check Path Filter + uses: dorny/paths-filter@v3 + id: filter + with: + filters: | + code: + - 'src/main/java/**' + - 'src/test/**' + - name: Setup Java + if: steps.filter.outputs.code == 'true' + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: '21' + - name: Setup Gradle + if: steps.filter.outputs.code == 'true' + uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: true + - name: Run Spotless Formatting Check with Gradle + if: steps.filter.outputs.code == 'true' + run: chmod +x ./gradlew && ./gradlew spotlessCheck --warning-mode all diff --git a/build.gradle b/build.gradle index ac53a560..a79d0f02 100755 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { id 'maven-publish' alias libs.plugins.modDevGradle //alias libs.plugins.shadow - alias libs.plugins.editorconfig + alias libs.plugins.spotless alias libs.plugins.lombok } @@ -66,7 +66,7 @@ apply from: "$rootDir/gradle/scripts/repositories.gradle" apply from: "$rootDir/dependencies.gradle" apply from: "$rootDir/gradle/scripts/resources.gradle" apply from: "$rootDir/gradle/scripts/publishing.gradle" -apply from: "$rootDir/gradle/scripts/formatting.gradle" +apply from: "$rootDir/gradle/scripts/spotless.gradle" apply from: "$rootDir/gradle/scripts/docs.gradle" diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 11cd6f38..6e9d33bd 100755 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,7 +5,7 @@ neoForge = "21.1.265" loader = "4" parchment = "2024.11.17" # https://parchmentmc.org/docs/getting-started shadow = "8.3.5" -editorconfig = "0.1.0" +spotless = "8.1.0" modDevGradle = "2.0.86" lombok = "8.14" @@ -27,5 +27,5 @@ mcdevAnnotations = { module = "com.demonwav.mcdev:annotations", version.ref = "m [plugins] modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGradle" } shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } -editorconfig = { id = "org.ec4j.editorconfig", version.ref = "editorconfig" } +spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } lombok = { id = "io.freefair.lombok", version.ref = "lombok" } diff --git a/gradle/scripts/formatting.gradle b/gradle/scripts/formatting.gradle deleted file mode 100644 index 677adf1c..00000000 --- a/gradle/scripts/formatting.gradle +++ /dev/null @@ -1,6 +0,0 @@ -// EditorConfig auto-formatter -// See https://github.com/ec4j/editorconfig-gradle-plugin -// Can be locally toggled via @formatter:off/@formatter:on comments -editorconfig { - includes = ['*'] -} diff --git a/gradle/scripts/spotless.gradle b/gradle/scripts/spotless.gradle new file mode 100644 index 00000000..225a5a8f --- /dev/null +++ b/gradle/scripts/spotless.gradle @@ -0,0 +1,27 @@ +// Spotless auto-formatter +// See https://github.com/diffplug/spotless/tree/main/plugin-gradle +// Can be locally toggled via spotless:off/spotless:on comments +spotless { + encoding 'UTF-8' + ratchetFrom 'origin/1.21.1' + + format 'misc', { + target '.gitignore' + + trimTrailingWhitespace() + leadingTabsToSpaces() + endWithNewline() + } + java { + target 'src/main/java/**/*.java', 'src/test/java/**/*.java' + + def orderFile = file("$rootDir/spotless/spotless.importorder") + def formatFile = file("$rootDir/spotless/spotless.eclipseformat.xml") + + toggleOffOn() + importOrderFile(orderFile) + removeUnusedImports('cleanthat-javaparser-unnecessaryimport') + endWithNewline() + eclipse('4.36').configFile(formatFile) + } +} diff --git a/spotless/spotless.eclipseformat.xml b/spotless/spotless.eclipseformat.xml new file mode 100644 index 00000000..8db01de4 --- /dev/null +++ b/spotless/spotless.eclipseformat.xml @@ -0,0 +1,400 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spotless/spotless.importorder b/spotless/spotless.importorder new file mode 100644 index 00000000..5c05beb3 --- /dev/null +++ b/spotless/spotless.importorder @@ -0,0 +1,7 @@ +#Organize Import Order +0=brachy +1=net +2= +3=java +4=javax +5=\# diff --git a/src/main/java/brachy/modularui/ModularUI.java b/src/main/java/brachy/modularui/ModularUI.java index 7e3cddf5..9918fd84 100644 --- a/src/main/java/brachy/modularui/ModularUI.java +++ b/src/main/java/brachy/modularui/ModularUI.java @@ -14,7 +14,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import com.mojang.brigadier.Command; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.ModContainer; import net.neoforged.fml.ModList; @@ -32,6 +31,7 @@ import net.neoforged.neoforge.event.tick.PlayerTickEvent; import net.neoforged.neoforge.server.ServerLifecycleHooks; +import com.mojang.brigadier.Command; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; @@ -122,7 +122,7 @@ public static boolean isClientThread() { /** * @return if the game is the PHYSICAL client, e.g. not a dedicated server. * @apiNote Do not use this to check if you're currently on the server thread for side-specific actions! - * It does NOT work for that. Use {@link #isClientThread()} instead. + * It does NOT work for that. Use {@link #isClientThread()} instead. * @see #isClientThread() */ public static boolean isClientSide() { @@ -133,7 +133,7 @@ public static boolean isClientSide() { * This check isn't the same for client and server! * * @return if it's safe to access the current instance {@link net.minecraft.world.level.Level Level} on client or if - * it's safe to access any level on server. + * it's safe to access any level on server. */ public static boolean canGetServerLevel() { if (isClientSide()) { @@ -173,7 +173,8 @@ private void onRegisterCommand(RegisterCommandsEvent event) { .executes(ctx -> { ThemeManager.reload(); // TODO translations for this - ctx.getSource().sendSuccess(() -> Component.literal("ModularUI Themes reloaded").withStyle(Text.GREEN), true); + ctx.getSource().sendSuccess( + () -> Component.literal("ModularUI Themes reloaded").withStyle(Text.GREEN), true); return Command.SINGLE_SUCCESS; })); event.getDispatcher().register(command); @@ -181,14 +182,14 @@ private void onRegisterCommand(RegisterCommandsEvent event) { public enum Mods { - //BLUR(ModIds.BLUR), - //BOGOSORTER(ModIds.BOGOSORTER), + // BLUR(ModIds.BLUR), + // BOGOSORTER(ModIds.BOGOSORTER), CURIOS(ModIds.CURIOS), EMI(ModIds.EMI), JEI(ModIds.JEI), REI(ModIds.REI), - //MODNAMETOOLTIP(ModIds.MODNAMETOOLTIP), - //NEA(ModIds.NEA), + // MODNAMETOOLTIP(ModIds.MODNAMETOOLTIP), + // NEA(ModIds.NEA), SODIUM(ModIds.SODIUM), IRIS(ModIds.IRIS); diff --git a/src/main/java/brachy/modularui/ModularUIConfig.java b/src/main/java/brachy/modularui/ModularUIConfig.java index 1d91af6c..c5537fda 100644 --- a/src/main/java/brachy/modularui/ModularUIConfig.java +++ b/src/main/java/brachy/modularui/ModularUIConfig.java @@ -1,7 +1,6 @@ package brachy.modularui; import brachy.modularui.screen.RichTooltip; -import brachy.modularui.utils.Color; import net.minecraft.ChatFormatting; import net.neoforged.neoforge.common.ModConfigSpec; @@ -27,7 +26,8 @@ public class ModularUIConfig { .translation("config.modularui.defaultScrollSpeed") .defineInRange("defaultScrollSpeed", 30, 1, 100); public static final BooleanValue SMOOTH_PROGRESS_BARS = BUILDER - .comment("If progress bars should step in texture pixels or screen pixels. (Screen pixels are way smaller and therefore smoother)") + .comment( + "If progress bars should step in texture pixels or screen pixels. (Screen pixels are way smaller and therefore smoother)") .translation("config.modularui.smoothProgressBars") .define("smoothProgressBars", false); public static final IntValue ANIMATION_TIME = BUILDER @@ -40,7 +40,8 @@ public class ModularUIConfig { .translation("config.modularui.tooltipPos") .defineEnum("tooltipPos", RichTooltip.Pos.NEXT_TO_MOUSE); public static final BooleanValue ESC_RESTORES_LAST_TEXT = BUILDER - .comment("If true, pressing ESC key in the text field will restore the last text instead of confirming current one.") + .comment( + "If true, pressing ESC key in the text field will restore the last text instead of confirming current one.") .translation("config.modularui.escRestoresLastText") .define("escRestoresLastText", false); public static final BooleanValue USE_DARK_THEME_BY_DEFAULT = BUILDER diff --git a/src/main/java/brachy/modularui/ModularUIMenuTypes.java b/src/main/java/brachy/modularui/ModularUIMenuTypes.java index 3a3e7b89..d785810a 100644 --- a/src/main/java/brachy/modularui/ModularUIMenuTypes.java +++ b/src/main/java/brachy/modularui/ModularUIMenuTypes.java @@ -11,11 +11,13 @@ public class ModularUIMenuTypes { - private static final DeferredRegister> MENU_TYPES = DeferredRegister.create(Registries.MENU, ModularUI.MOD_ID); + private static final DeferredRegister> MENU_TYPES = DeferredRegister.create(Registries.MENU, + ModularUI.MOD_ID); - public static final DeferredHolder, MenuType> MODULAR_CONTAINER = MENU_TYPES.register( - "modular", - () -> IMenuTypeExtension.create(ModularContainerMenu::new)); + public static final DeferredHolder, MenuType> MODULAR_CONTAINER = MENU_TYPES + .register( + "modular", + () -> IMenuTypeExtension.create(ModularContainerMenu::new)); public static void register(IEventBus modBus) { MENU_TYPES.register(modBus); diff --git a/src/main/java/brachy/modularui/api/IPanelHandler.java b/src/main/java/brachy/modularui/api/IPanelHandler.java index 1b9dd650..2af44dda 100644 --- a/src/main/java/brachy/modularui/api/IPanelHandler.java +++ b/src/main/java/brachy/modularui/api/IPanelHandler.java @@ -20,7 +20,8 @@ * With the difference, that the method from this interface also works on server * side. *

- * Synced panels must be created with {@link PanelSyncManager#syncedPanel(String, boolean, PanelSyncHandler.IPanelBuilder)}. + * Synced panels must be created with + * {@link PanelSyncManager#syncedPanel(String, boolean, PanelSyncHandler.IPanelBuilder)}. * If the panel does not contain any synced widgets, a simple panel handler using * {@link #simple(ModularPanel, SecondaryPanel.IPanelBuilder, boolean)} * is likely what you need. diff --git a/src/main/java/brachy/modularui/api/ITheme.java b/src/main/java/brachy/modularui/api/ITheme.java index 60059cbf..4d38ad15 100644 --- a/src/main/java/brachy/modularui/api/ITheme.java +++ b/src/main/java/brachy/modularui/api/ITheme.java @@ -11,12 +11,8 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.Encoder; - import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; - -import net.minecraft.util.ExtraCodecs; - import org.jetbrains.annotations.UnmodifiableView; import java.util.Collection; @@ -39,6 +35,7 @@ public interface ITheme { ITheme::getId); Encoder ENCODER = new Encoder<>() { + @Override public DataResult encode(ITheme input, DynamicOps ops, T prefix) { var mapBuilder = ops.mapBuilder(); @@ -49,7 +46,8 @@ public DataResult encode(ITheme input, DynamicOps ops, T prefix) { for (WidgetThemeEntry entry : input.getWidgetThemeEntries()) { if (entry.key() == IThemeApi.FALLBACK) continue; var set = encodedThemes.computeIfAbsent(entry.key().getName(), k -> new ObjectOpenHashSet<>()); - if (entry.key().isSubWidgetTheme() && set.contains(entry.theme()) && set.contains(entry.hoverTheme())) continue; + if (entry.key().isSubWidgetTheme() && set.contains(entry.theme()) && set.contains(entry.hoverTheme())) + continue; entry.encode(ops, mapBuilder, false); set.add(entry.theme()); set.add(entry.hoverTheme()); diff --git a/src/main/java/brachy/modularui/api/IThemeApi.java b/src/main/java/brachy/modularui/api/IThemeApi.java index d1f2bb90..5846de0e 100644 --- a/src/main/java/brachy/modularui/api/IThemeApi.java +++ b/src/main/java/brachy/modularui/api/IThemeApi.java @@ -19,7 +19,6 @@ import brachy.modularui.utils.serialization.json.JsonBuilder; import com.mojang.serialization.Codec; - import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -191,7 +190,8 @@ default void registerTheme(ThemeBuilder themeBuilder) { * @param defaultTheme default theme if no theme was found * @return the registered theme for the given screen or the given default theme or {@link #getDefaultTheme()} */ - default ITheme getThemeForScreen(String owner, String name, @Nullable String defaultTheme, @Nullable String fallbackTheme) { + default ITheme getThemeForScreen(String owner, String name, @Nullable String defaultTheme, + @Nullable String fallbackTheme) { return getThemeForScreen(owner, name, null, defaultTheme, fallbackTheme); } @@ -204,7 +204,8 @@ default ITheme getThemeForScreen(String owner, String name, @Nullable String def * @param defaultTheme default theme if no theme was found * @return the registered theme for the given screen or the given default theme or {@link #getDefaultTheme()} */ - ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, @Nullable String fallbackTheme); + ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, + @Nullable String fallbackTheme); /** * Gets the appropriate theme for a specific panel. @@ -215,7 +216,8 @@ default ITheme getThemeForScreen(String owner, String name, @Nullable String def */ default ITheme getThemeForScreen(ModularPanel panel, @Nullable String defaultTheme) { ModularScreen screen = panel.getScreen(); - return getThemeForScreen(screen.getOwner(), screen.getName(), panel.getName(), defaultTheme, screen.getThemeOverride()); + return getThemeForScreen(screen.getOwner(), screen.getName(), panel.getName(), defaultTheme, + screen.getThemeOverride()); } /** @@ -250,7 +252,8 @@ default void registerThemeForScreen(String owner, String name, String theme) { @Deprecated WidgetThemeKey registerWidgetTheme(String id, T defaultTheme, T defaultHoverTheme, - WidgetThemeMerger merger, WidgetThemeCodec codec); + WidgetThemeMerger merger, + WidgetThemeCodec codec); default WidgetThemeKeyBuilder widgetThemeKeyBuilder(String id, Class type) { return new WidgetThemeKeyBuilder<>(id, type); diff --git a/src/main/java/brachy/modularui/api/ITreeNode.java b/src/main/java/brachy/modularui/api/ITreeNode.java index e1d6bcc9..ad098a8d 100644 --- a/src/main/java/brachy/modularui/api/ITreeNode.java +++ b/src/main/java/brachy/modularui/api/ITreeNode.java @@ -1,7 +1,7 @@ package brachy.modularui.api; -import it.unimi.dsi.fastutil.objects.ObjectList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectList; import java.util.List; import java.util.function.Predicate; diff --git a/src/main/java/brachy/modularui/api/drawable/IDrawable.java b/src/main/java/brachy/modularui/api/drawable/IDrawable.java index e6a0f859..b0d6147a 100644 --- a/src/main/java/brachy/modularui/api/drawable/IDrawable.java +++ b/src/main/java/brachy/modularui/api/drawable/IDrawable.java @@ -14,14 +14,14 @@ import brachy.modularui.widget.Widget; import brachy.modularui.widget.sizer.Area; -import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.JsonOps; -import com.mojang.serialization.MapCodec; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import com.google.gson.JsonElement; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; import org.jetbrains.annotations.Nullable; /** @@ -45,6 +45,7 @@ static IDrawable of(IDrawable... drawables) { * An empty drawable. Does nothing. */ IDrawable EMPTY = new IDrawable() { + @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) {} @@ -58,6 +59,7 @@ public String toString() { * An empty drawable used to mark hover textures as "should not be used"! */ IDrawable NONE = new IDrawable() { + @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) {} @@ -68,7 +70,8 @@ public String toString() { }; CodecRegistry CODECS = new CodecRegistry<>(); - MapCodec CODEC_DISPATCH = CodecUtil.dispatchNullable(Codec.STRING, IDrawable::getTypeName, CODECS::getNullable); + MapCodec CODEC_DISPATCH = CodecUtil.dispatchNullable(Codec.STRING, IDrawable::getTypeName, + CODECS::getNullable); Codec CODEC_EMPTY_NONE = Codec.STRING.flatXmap(s -> { if (s == null || s.equals("empty") || s.equals("null")) return DataResult.success(EMPTY); if (s.equals("none")) return DataResult.success(NONE); @@ -168,7 +171,8 @@ default void drawAtZero(GuiContext context, Area area, WidgetTheme widgetTheme) */ @OnlyIn(Dist.CLIENT) default void drawAtZeroPadded(GuiContext context, Area area, WidgetTheme widgetTheme) { - draw(context, area.getPadding().left(), area.getPadding().top(), area.paddedWidth(), area.paddedHeight(), widgetTheme); + draw(context, area.getPadding().left(), area.getPadding().top(), area.paddedWidth(), area.paddedHeight(), + widgetTheme); } /** diff --git a/src/main/java/brachy/modularui/api/drawable/ITextLine.java b/src/main/java/brachy/modularui/api/drawable/ITextLine.java index b5621525..e0601e66 100644 --- a/src/main/java/brachy/modularui/api/drawable/ITextLine.java +++ b/src/main/java/brachy/modularui/api/drawable/ITextLine.java @@ -10,7 +10,8 @@ public interface ITextLine { int getHeight(Font font); - void draw(GuiContext context, Font font, float x, float y, int color, boolean shadow, int availableWidth, int availableHeight); + void draw(GuiContext context, Font font, float x, float y, int color, boolean shadow, int availableWidth, + int availableHeight); Object getHoveringElement(Font font, int x, int y); } diff --git a/src/main/java/brachy/modularui/api/drawable/Text.java b/src/main/java/brachy/modularui/api/drawable/Text.java index 6f8a59db..e8220cdc 100644 --- a/src/main/java/brachy/modularui/api/drawable/Text.java +++ b/src/main/java/brachy/modularui/api/drawable/Text.java @@ -10,8 +10,6 @@ import brachy.modularui.utils.Alignment; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.demonwav.mcdev.annotations.Translatable; - import net.minecraft.ChatFormatting; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; @@ -19,6 +17,7 @@ import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.demonwav.mcdev.annotations.Translatable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -157,7 +156,8 @@ default void draw(GuiContext context, int x, int y, int width, int height, Widge } @OnlyIn(Dist.CLIENT) - default void drawAligned(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme, Alignment alignment) { + default void drawAligned(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme, + Alignment alignment) { renderer.setColor(widgetTheme.getTextColor()); renderer.setShadow(widgetTheme.isTextShadow()); renderer.setAlignment(alignment, width, height); @@ -201,9 +201,11 @@ default float getScale() { ModularComponent withStyle(); - /*default AnimatedText withAnimation() { - return new AnimatedText(this); - }*/ + /* + * default AnimatedText withAnimation() { + * return new AnimatedText(this); + * } + */ /** * Set text formatting to this key. If {@link Text#RESET} is used, then that's applied first and then all other diff --git a/src/main/java/brachy/modularui/api/layout/IViewportStack.java b/src/main/java/brachy/modularui/api/layout/IViewportStack.java index cb7e6856..7662b632 100755 --- a/src/main/java/brachy/modularui/api/layout/IViewportStack.java +++ b/src/main/java/brachy/modularui/api/layout/IViewportStack.java @@ -4,7 +4,6 @@ import brachy.modularui.widget.sizer.Area; import com.mojang.blaze3d.vertex.PoseStack; - import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; diff --git a/src/main/java/brachy/modularui/api/value/IValue.java b/src/main/java/brachy/modularui/api/value/IValue.java index 77e33ea5..3e17c126 100644 --- a/src/main/java/brachy/modularui/api/value/IValue.java +++ b/src/main/java/brachy/modularui/api/value/IValue.java @@ -1,6 +1,5 @@ package brachy.modularui.api.value; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.UnknownNullability; /** diff --git a/src/main/java/brachy/modularui/api/value/sync/IBoolSyncValue.java b/src/main/java/brachy/modularui/api/value/sync/IBoolSyncValue.java index 19c464d7..c9479fb6 100644 --- a/src/main/java/brachy/modularui/api/value/sync/IBoolSyncValue.java +++ b/src/main/java/brachy/modularui/api/value/sync/IBoolSyncValue.java @@ -9,7 +9,8 @@ * * @param value type */ -public interface IBoolSyncValue extends IValueSyncHandler, IBoolValue, IIntSyncValue { +public interface IBoolSyncValue + extends IValueSyncHandler, IBoolValue, IIntSyncValue { @Override default void setBoolValue(boolean val) { diff --git a/src/main/java/brachy/modularui/api/widget/IDraggable.java b/src/main/java/brachy/modularui/api/widget/IDraggable.java index 252f36e0..2fd7500e 100644 --- a/src/main/java/brachy/modularui/api/widget/IDraggable.java +++ b/src/main/java/brachy/modularui/api/widget/IDraggable.java @@ -21,7 +21,8 @@ public interface IDraggable { /** * Gets called every frame after everything else is rendered. * Is only called when {@link #isMoving()} is true. - * Translate to the mouse pos and draw with {@link WidgetTree#drawTree(IWidget, ModularGuiContext, boolean, boolean)}. + * Translate to the mouse pos and draw with + * {@link WidgetTree#drawTree(IWidget, ModularGuiContext, boolean, boolean)}. * * @param graphics * @param partialTicks difference from last from diff --git a/src/main/java/brachy/modularui/api/widget/IPositioned.java b/src/main/java/brachy/modularui/api/widget/IPositioned.java index 9f65c924..b37ea882 100644 --- a/src/main/java/brachy/modularui/api/widget/IPositioned.java +++ b/src/main/java/brachy/modularui/api/widget/IPositioned.java @@ -15,7 +15,7 @@ * * @param widget type */ -@SuppressWarnings({"unused", "UnusedReturnValue"}) +@SuppressWarnings({ "unused", "UnusedReturnValue" }) public interface IPositioned> { /** @@ -62,8 +62,10 @@ default W coverChildrenHeight() { } /** - * Calculate the width by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the width by covering all children of this widget. For this calculation the widget children are used + * NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minWidth minimum width this widget can have, negative values disables cover children @@ -75,8 +77,10 @@ default W coverChildrenWidth(int minWidth) { } /** - * Calculate the height by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the height by covering all children of this widget. For this calculation the widget children are used + * NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minHeight minimum height this widget can have, negative values disables cover children @@ -97,8 +101,10 @@ default W coverChildren() { } /** - * Calculate the width and height by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the width and height by covering all children of this widget. For this calculation the widget children + * are used NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minSize minimum width and height this widget can have, negative values disables cover children @@ -109,8 +115,10 @@ default W coverChildren(int minSize) { } /** - * Calculate the width and height by covering all children of this widget. For this calculation the widget children are used NOT the resizer - * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this widgets size + * Calculate the width and height by covering all children of this widget. For this calculation the widget children + * are used NOT the resizer + * children. If a child position/size depends on this widget, its position/size is ignored and calculated after this + * widgets size * is calculated. If all children depend on this widgets size, the min size is used. * * @param minWidth minimum width this widget can have, negative values disables cover children @@ -149,7 +157,8 @@ default W disableCoverChildren() { } /** - * Sets if this resizer is decoration. Decoration will be ignored during coverChildren and margin/padding calculations. + * Sets if this resizer is decoration. Decoration will be ignored during coverChildren and margin/padding + * calculations. * * @param decoration true if this resizer is decoration * @return this @@ -167,7 +176,8 @@ default W decoration() { } /** - * Sets whether this widget should expand inside a {@link brachy.modularui.widgets.layout.Flow Flow} widget. Expanded means it takes + * Sets whether this widget should expand inside a {@link brachy.modularui.widgets.layout.Flow Flow} widget. + * Expanded means it takes * as much space as possible on the main axis without overlapping with other children in the flow. * * @return this @@ -190,8 +200,10 @@ default W relative(Area area) { } /** - * Sets the resizer this widget should be relative to. That means all left, top, right, bottom, width and height properties will be - * calculated based of the new resizer. By default, this is the widgets parent. Every resize node tree configuration is allowed as long + * Sets the resizer this widget should be relative to. That means all left, top, right, bottom, width and height + * properties will be + * calculated based of the new resizer. By default, this is the widgets parent. Every resize node tree configuration + * is allowed as long * as there are no circular dependencies. * * @param resizeNode resizer parent override @@ -239,7 +251,8 @@ default W left(int val) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0). * 0.0 means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. * * @param val relative left edge to parent left edge distance @@ -251,9 +264,12 @@ default W leftRel(float val) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative left edge to parent left edge distance * @param offset additional distance offset in pixel @@ -265,14 +281,18 @@ default W leftRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRelAnchor(float val, float anchor) { @@ -281,17 +301,22 @@ default W leftRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRel(float val, int offset, float anchor) { @@ -300,18 +325,24 @@ default W leftRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val left edge to parent left edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W left(float val, int offset, float anchor, Unit.Measure measure) { @@ -332,9 +363,12 @@ default W left(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative left edge to parent left edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -346,14 +380,18 @@ default W leftRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRelAnchor(DoubleSupplier val, float anchor) { @@ -362,17 +400,22 @@ default W leftRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets left edge to the resizers widget left edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the parent right edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the right edge touches the + * parent right edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative left edge to parent left edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W leftRel(DoubleSupplier val, int offset, float anchor) { @@ -392,7 +435,8 @@ default W right(int val) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0). * 0.0 means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. * * @param val relative right edge to parent right edge distance @@ -404,9 +448,12 @@ default W rightRel(float val) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative right edge to parent right edge distance * @param offset additional distance offset in pixel @@ -418,14 +465,18 @@ default W rightRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRelAnchor(float val, float anchor) { @@ -434,17 +485,22 @@ default W rightRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRel(float val, int offset, float anchor) { @@ -453,18 +509,24 @@ default W rightRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val right edge to parent right edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W right(float val, int offset, float anchor, Unit.Measure measure) { @@ -485,9 +547,12 @@ default W right(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative right edge to parent right edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -499,14 +564,18 @@ default W rightRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRelAnchor(DoubleSupplier val, float anchor) { @@ -515,17 +584,22 @@ default W rightRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets right edge to the resizers widget right edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches the parent left edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the right edge touches the parent right edge. 1.0 means the left edge touches + * the parent left edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative right edge to parent right edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W rightRel(DoubleSupplier val, int offset, float anchor) { @@ -545,7 +619,8 @@ default W top(int val) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0). * 0.0 means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. * * @param val relative top edge to parent top edge distance @@ -557,9 +632,12 @@ default W topRel(float val) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative top edge to parent top edge distance * @param offset additional distance offset in pixel @@ -571,14 +649,18 @@ default W topRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRelAnchor(float val, float anchor) { @@ -587,17 +669,22 @@ default W topRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRel(float val, int offset, float anchor) { @@ -606,18 +693,24 @@ default W topRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val top edge to parent top edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W top(float val, int offset, float anchor, Unit.Measure measure) { @@ -638,9 +731,12 @@ default W top(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative top edge to parent top edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -652,14 +748,18 @@ default W topRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an anchor. + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRelAnchor(DoubleSupplier val, float anchor) { @@ -668,17 +768,22 @@ default W topRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets top edge to the resizers widget top edge (usually between 0.0 and + * 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the parent bottom edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the top edge touches the parent top edge. 1.0 means the bottom edge touches the + * parent bottom edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative top edge to parent top edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W topRel(DoubleSupplier val, int offset, float anchor) { @@ -698,7 +803,8 @@ default W bottom(int val) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0). + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0). * 0.0 means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. * * @param val relative bottom edge to parent bottom edge distance @@ -710,9 +816,12 @@ default W bottomRel(float val) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel @@ -724,14 +833,18 @@ default W bottomRelOffset(float val, int offset) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRelAnchor(float val, float anchor) { @@ -740,17 +853,22 @@ default W bottomRelAnchor(float val, float anchor) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRel(float val, int offset, float anchor) { @@ -759,18 +877,24 @@ default W bottomRel(float val, int offset, float anchor) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value - * @param measure determines if the val param should be a relative value or in pixel, the anchor does nothing in pixel + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value + * @param measure determines if the val param should be a relative value or in pixel, the anchor does + * nothing in pixel * @return this */ default W bottom(float val, int offset, float anchor, Unit.Measure measure) { @@ -779,7 +903,8 @@ default W bottom(float val, int offset, float anchor, Unit.Measure measure) { } /** - * Sets the distance from this widgets bottom edge to the resizers widget bottom edge in pixel or as a relative value. + * Sets the distance from this widgets bottom edge to the resizers widget bottom edge in pixel or as a relative + * value. * * @param val bottom edge to parent bottom edge distance function which is called on every resize * @param measure determines if the val param should be a relative value or in pixel @@ -791,9 +916,12 @@ default W bottom(DoubleSupplier val, Unit.Measure measure) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset. - * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset. + * 0.0 for the relative value means the left edge touches the parent left edge. 1.0 means the top edge touches the + * parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. * * @param val relative bottom edge to parent bottom edge distance function which is called on every resize * @param offset additional distance offset in pixel @@ -805,14 +933,18 @@ default W bottomRelOffset(DoubleSupplier val, int offset) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an anchor. - * 0.0 for the relative value means the bottom edge touches the parent left bottom. 1.0 means the top edge touches the parent top edge. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an anchor. + * 0.0 for the relative value means the bottom edge touches the parent left bottom. 1.0 means the top edge touches + * the parent top edge. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance function which is called on every resize - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRelAnchor(DoubleSupplier val, float anchor) { @@ -821,17 +953,22 @@ default W bottomRelAnchor(DoubleSupplier val, float anchor) { } /** - * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 and 1.0) with an offset + * Sets the relative distance from this widgets bottom edge to the resizers widget bottom edge (usually between 0.0 + * and 1.0) with an offset * and an anchor. - * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches the parent top edge. - * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be negative. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. By default, + * 0.0 for the relative value means the bottom edge touches the parent bottom edge. 1.0 means the top edge touches + * the parent top edge. + * The offset is in pixel and is added after the position with the relative value is calculated. The offset can be + * negative. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. By default, * the anchor is equal to the relative value. The formular for calculating the position is * parentSize * relativeValue - selfSize * anchor. * * @param val relative bottom edge to parent bottom edge distance * @param offset additional distance offset in pixel - * @param anchor determines the relative position which is used to calculate the actual position with the relative value + * @param anchor determines the relative position which is used to calculate the actual position with the relative + * value * @return this */ default W bottomRel(DoubleSupplier val, int offset, float anchor) { @@ -863,7 +1000,8 @@ default W widthRel(float val) { /** * Sets the relative width of this widget with an offset. 1.0 is the same size as the resizer parent. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative width * @param offset additional size offset in pixel @@ -888,7 +1026,8 @@ default W width(float val, Unit.Measure measure) { /** * Sets the width of this widget in pixel or as a relative value with an offset. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative width function which is called on every resize * @param offset additional size offset in pixel @@ -947,7 +1086,8 @@ default W height(float val, Unit.Measure measure) { /** * Sets the relative height of this widget with an offset. 1.0 is the same size as the resizer parent. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative height * @param offset additional size offset in pixel @@ -960,7 +1100,8 @@ default W heightRelOffset(float val, int offset) { /** * Sets the width of this widget in pixel or as a relative value with an offset. - * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be negative. + * The offset is in pixel and is added after the size with the relative value is calculated. The offset can be + * negative. * * @param val relative width function which is called on every resize * @param offset additional size offset in pixel @@ -1008,7 +1149,8 @@ default W posRel(float x, float y) { } /** - * Sets the relative position with an {@link Alignment}. Combines {@link #leftRel(float)} and {@link #topRel(float)}. + * Sets the relative position with an {@link Alignment}. Combines {@link #leftRel(float)} and + * {@link #topRel(float)}. * * @param alignment relative position * @return this @@ -1031,7 +1173,8 @@ default W size(int w, int h) { } /** - * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and {@link #heightRel(float)}. + * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and + * {@link #heightRel(float)}. * * @param w relative width * @param h relative height @@ -1053,7 +1196,8 @@ default W size(int val) { } /** - * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and {@link #heightRel(float)}. + * Sets the relative width and height of this widget. Combines {@link #widthRel(float)} and + * {@link #heightRel(float)}. * * @param val relative width and height * @return this @@ -1091,7 +1235,8 @@ default W full() { /** * Sets the anchor on the left side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the left side * @return this @@ -1103,7 +1248,8 @@ default W anchorLeft(float val) { /** * Sets the anchor on the right side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the right side * @return this @@ -1115,7 +1261,8 @@ default W anchorRight(float val) { /** * Sets the anchor on the top side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the top side * @return this @@ -1127,7 +1274,8 @@ default W anchorTop(float val) { /** * Sets the anchor on the bottom side of the widget. - * The anchor determines what relative position inside this widget is used to calculate the relative position of the widget. + * The anchor determines what relative position inside this widget is used to calculate the relative position of the + * widget. * * @param val anchor on the bottom side * @return this diff --git a/src/main/java/brachy/modularui/api/widget/IWidget.java b/src/main/java/brachy/modularui/api/widget/IWidget.java index a7278df5..0b7cdfe6 100644 --- a/src/main/java/brachy/modularui/api/widget/IWidget.java +++ b/src/main/java/brachy/modularui/api/widget/IWidget.java @@ -13,9 +13,8 @@ import brachy.modularui.widget.sizer.Area; import brachy.modularui.widget.sizer.StandardResizer; -import com.mojang.serialization.Codec; - import com.google.common.base.CharMatcher; +import com.mojang.serialization.Codec; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectList; import org.jetbrains.annotations.NotNull; @@ -75,7 +74,8 @@ default boolean hasParent() { /** * @return the panel this widget is in */ - @NotNull ModularPanel getPanel(); + @NotNull + ModularPanel getPanel(); /** * @return the area this widget occupies @@ -298,6 +298,7 @@ default WidgetThemeEntry getWidgetThemeEntry(ITheme theme) { /** * Gets the theme that is currently in use for this widget. + * * @return The gui theme. */ ITheme getTheme(); diff --git a/src/main/java/brachy/modularui/api/widget/Interactable.java b/src/main/java/brachy/modularui/api/widget/Interactable.java index 1985c28e..72874b72 100755 --- a/src/main/java/brachy/modularui/api/widget/Interactable.java +++ b/src/main/java/brachy/modularui/api/widget/Interactable.java @@ -4,10 +4,10 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.sounds.SoundEvents; -import com.mojang.blaze3d.platform.InputConstants; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.blaze3d.platform.InputConstants; import org.jetbrains.annotations.NotNull; import org.lwjgl.glfw.GLFW; @@ -22,8 +22,8 @@ public interface Interactable { * * @param button mouse button that was pressed. * @return result that determines what happens to other widgets - * {@link #onMouseTapped(int)} is only called if this returns {@link Result#ACCEPT} or - * {@link Result#SUCCESS} + * {@link #onMouseTapped(int)} is only called if this returns {@link Result#ACCEPT} or + * {@link Result#SUCCESS} */ @NotNull default Result onMousePressed(int button) { @@ -35,7 +35,7 @@ default Result onMousePressed(int button) { * * @param button mouse button that was released. * @return whether other widgets should get called to. If this returns false, - * {@link #onMouseTapped(int)} will NOT be called. + * {@link #onMouseTapped(int)} will NOT be called. */ default boolean onMouseReleased(int button) { return false; @@ -46,9 +46,9 @@ default boolean onMouseReleased(int button) { * * @param button mouse button that was pressed. * @return result that determines if other widgets should get tapped to - * {@link Result#IGNORE IGNORE} and {@link Result#ACCEPT ACCEPT} will both "ignore" the result and - * {@link Result#STOP STOP} and {@link Result#SUCCESS SUCCESS} will both stop other widgets - * from getting tapped. + * {@link Result#IGNORE IGNORE} and {@link Result#ACCEPT ACCEPT} will both "ignore" the result and + * {@link Result#STOP STOP} and {@link Result#SUCCESS SUCCESS} will both stop other widgets + * from getting tapped. */ @NotNull default Result onMouseTapped(int button) { @@ -62,8 +62,8 @@ default Result onMouseTapped(int button) { * @param scanCode character that was pressed. * @param modifiers any modifiers that were used. * @return result that determines what happens to other widgets - * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or - * {@link Result#SUCCESS} + * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or + * {@link Result#SUCCESS} */ @NotNull default Result onKeyPressed(int keyCode, int scanCode, int modifiers) { @@ -77,7 +77,7 @@ default Result onKeyPressed(int keyCode, int scanCode, int modifiers) { * @param scanCode character that was pressed. * @param modifiers any modifiers that were used. * @return whether other widgets should get called too. If this returns false, {@link #onKeyTapped(int, int, int)} - * will NOT be called. + * will NOT be called. */ default boolean onKeyReleased(int keyCode, int scanCode, int modifiers) { return false; @@ -90,8 +90,8 @@ default boolean onKeyReleased(int keyCode, int scanCode, int modifiers) { * @param scanCode character that was pressed. * @param modifiers any modifiers that were used. * @return result that determines if other widgets should get tapped to - * {@link Result#IGNORE} and {@link Result#ACCEPT} will both "ignore" the result and {@link Result#STOP} and - * {@link Result#SUCCESS} will both stop other widgets from getting tapped. + * {@link Result#IGNORE} and {@link Result#ACCEPT} will both "ignore" the result and {@link Result#STOP} and + * {@link Result#SUCCESS} will both stop other widgets from getting tapped. */ @NotNull default Result onKeyTapped(int keyCode, int scanCode, int modifiers) { @@ -104,8 +104,8 @@ default Result onKeyTapped(int keyCode, int scanCode, int modifiers) { * @param codePoint character that was typed * @param modifiers any modifiers that were used. * @return result that determines what happens to other widgets - * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or - * {@link Result#SUCCESS} + * {@link #onKeyTapped(int, int, int)} is only called if this returns {@link Result#ACCEPT} or + * {@link Result#SUCCESS} */ @NotNull default Result onCharTyped(char codePoint, int modifiers) { diff --git a/src/main/java/brachy/modularui/client/ModularUIClient.java b/src/main/java/brachy/modularui/client/ModularUIClient.java index ddb0dba9..a5e522a0 100644 --- a/src/main/java/brachy/modularui/client/ModularUIClient.java +++ b/src/main/java/brachy/modularui/client/ModularUIClient.java @@ -18,13 +18,10 @@ import brachy.modularui.screen.ModularContainerMenu; import brachy.modularui.test.TestHandler; import brachy.modularui.theme.ThemeManager; +import brachy.modularui.utils.CursorHandler; import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; - -import brachy.modularui.utils.CursorHandler; - -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.world.entity.player.Player; import net.neoforged.api.distmarker.Dist; @@ -36,13 +33,13 @@ import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; import net.neoforged.neoforge.client.event.RegisterClientTooltipComponentFactoriesEvent; import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.level.LevelEvent; +import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.floats.FloatUnaryOperator; import lombok.Getter; -import net.neoforged.neoforge.common.NeoForge; -import net.neoforged.neoforge.event.level.LevelEvent; - import java.util.function.Function; @Mod(value = ModularUI.MOD_ID, dist = Dist.CLIENT) diff --git a/src/main/java/brachy/modularui/core/mixins/client/AbstractWidgetMixin.java b/src/main/java/brachy/modularui/core/mixins/client/AbstractWidgetMixin.java index 113647fb..78d0ff43 100644 --- a/src/main/java/brachy/modularui/core/mixins/client/AbstractWidgetMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/client/AbstractWidgetMixin.java @@ -23,8 +23,8 @@ public abstract class AbstractWidgetMixin { @Inject(method = "render", at = @At(value = "FIELD", - opcode = Opcodes.PUTFIELD, - target = "Lnet/minecraft/client/gui/components/AbstractWidget;isHovered:Z")) + opcode = Opcodes.PUTFIELD, + target = "Lnet/minecraft/client/gui/components/AbstractWidget;isHovered:Z")) public void mui$fixHoveredState(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick, CallbackInfo ci) { // fixes buttons being hovered when an overlay element is already hovered diff --git a/src/main/java/brachy/modularui/core/mixins/client/GuiGraphicsMixin.java b/src/main/java/brachy/modularui/core/mixins/client/GuiGraphicsMixin.java index b18f1f68..72bdcff2 100644 --- a/src/main/java/brachy/modularui/core/mixins/client/GuiGraphicsMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/client/GuiGraphicsMixin.java @@ -1,115 +1,103 @@ package brachy.modularui.core.mixins.client; -import brachy.modularui.ModularUIConfig; -import brachy.modularui.drawable.text.FontRenderHelper; -import brachy.modularui.screen.RichTooltip; -import brachy.modularui.screen.viewport.GuiContext; - -import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.FormattedText; -import net.minecraft.util.FormattedCharSequence; -import net.minecraft.world.inventory.tooltip.TooltipComponent; -import net.minecraft.world.item.ItemStack; -import com.llamalad7.mixinextras.sugar.Local; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; @Mixin(GuiGraphics.class) public abstract class GuiGraphicsMixin { -/* - @Shadow(remap = false) - private ItemStack tooltipStack; - - @Inject(method = "renderTooltip(Lnet/minecraft/client/gui/Font;Ljava/util/List;Ljava/util/Optional;II)V", - at = @At(value = "HEAD"), - cancellable = true) - private void mui$replaceWithRichTooltip(Font font, List tooltipLines, - Optional visualComponent, int mouseX, int mouseY, - CallbackInfo ci) { - // funny cast to get from List to List - // I just don't want to copy the list unnecessarily - // this is safe because Component extends FormattedText - // noinspection unchecked - mui$drawRichTooltip(font, (List) (List) tooltipLines, visualComponent, mouseX, mouseY, ci); - } - - @Inject( - method = { - "renderTooltip(Lnet/minecraft/client/gui/Font;Ljava/util/List;Lnet/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipPositioner;II)V", - "renderTooltip(Lnet/minecraft/client/gui/Font;Ljava/util/List;II)V" - }, - at = @At(value = "HEAD"), - cancellable = true) - private void mui$replaceWithRichTooltip(CallbackInfo ci, - @Local(argsOnly = true) Font font, - @Local(argsOnly = true) List tooltipLines, - @Local(ordinal = 0, argsOnly = true) int mouseX, - @Local(ordinal = 1, argsOnly = true) int mouseY) { - List text = tooltipLines.stream() - .map(FontRenderHelper::getComponentFromCharSequence) - .collect(Collectors.toList()); - mui$drawRichTooltip(font, text, Optional.empty(), mouseX, mouseY, ci); - } - - @Inject(method = "renderComponentTooltip*", - at = @At( - value = "INVOKE", - target = "Lnet/neoforged/neoforge/client/ClientHooks;gatherTooltipComponents(Lnet/minecraft/world/item/ItemStack;Ljava/util/List;IIILnet/minecraft/client/gui/Font;)Ljava/util/List;", - remap = false), - cancellable = true) - private void mui$replaceWithRichTooltip2(CallbackInfo ci, - @Local(argsOnly = true) Font font, - @Local(argsOnly = true) List tooltipLines, - @Local(ordinal = 0, argsOnly = true) int mouseX, - @Local(ordinal = 1, argsOnly = true) int mouseY) { - mui$drawRichTooltip(font, tooltipLines, Optional.empty(), mouseX, mouseY, ci); - } - - @Unique - private void mui$drawRichTooltip(Font font, List textLines, - Optional tooltipComponent, int mouseX, int mouseY, - CallbackInfo ci) { - if (!ModularUIConfig.replaceVanillaTooltips() || textLines.isEmpty()) { - return; - } - - RichTooltip tooltip = new RichTooltip(); - tooltip.parent(area -> RichTooltip.findIngredientArea(area, mouseX, mouseY)); - // Other positions don't really work due to the lack of GuiContext in non-modular uis - tooltip.add(textLines.getFirst()).newLine(); - // vanilla inserts the bundle tooltip here so we should do it as the 2nd item too - tooltipComponent.ifPresent(tooltip::addLine); - - if (!this.tooltipStack.isEmpty()) { - tooltip.spaceLine(); - } - for (int i = 1, n = textLines.size(); i < n; i++) { - tooltip.add(textLines.get(i)).newLine(); - } - - GuiContext context = GuiContext.getDefault(); - GuiGraphics lastGraphics = context.getGraphics(); - - context.setOverrideFont(font); - context.setGraphics((GuiGraphics) (Object) this); - tooltip.draw(context, this.tooltipStack); - - context.setGraphics(lastGraphics); - // the override font is removed at the end of RichTooltip#draw; no need to duplicate that here - - // Cancel vanilla tooltip rendering - ci.cancel(); - } -*/ + /* + * @Shadow(remap = false) + * private ItemStack tooltipStack; + * + * @Inject(method = "renderTooltip(Lnet/minecraft/client/gui/Font;Ljava/util/List;Ljava/util/Optional;II)V", + * at = @At(value = "HEAD"), + * cancellable = true) + * private void mui$replaceWithRichTooltip(Font font, List tooltipLines, + * Optional visualComponent, int mouseX, int mouseY, + * CallbackInfo ci) { + * // funny cast to get from List to List + * // I just don't want to copy the list unnecessarily + * // this is safe because Component extends FormattedText + * // noinspection unchecked + * mui$drawRichTooltip(font, (List) (List) tooltipLines, visualComponent, mouseX, mouseY, ci); + * } + * + * @Inject( + * method = { + * "renderTooltip(Lnet/minecraft/client/gui/Font;Ljava/util/List;Lnet/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipPositioner;II)V", + * "renderTooltip(Lnet/minecraft/client/gui/Font;Ljava/util/List;II)V" + * }, + * at = @At(value = "HEAD"), + * cancellable = true) + * private void mui$replaceWithRichTooltip(CallbackInfo ci, + * + * @Local(argsOnly = true) Font font, + * + * @Local(argsOnly = true) List tooltipLines, + * + * @Local(ordinal = 0, argsOnly = true) int mouseX, + * + * @Local(ordinal = 1, argsOnly = true) int mouseY) { + * List text = tooltipLines.stream() + * .map(FontRenderHelper::getComponentFromCharSequence) + * .collect(Collectors.toList()); + * mui$drawRichTooltip(font, text, Optional.empty(), mouseX, mouseY, ci); + * } + * + * @Inject(method = "renderComponentTooltip*", + * at = @At( + * value = "INVOKE", + * target = + * "Lnet/neoforged/neoforge/client/ClientHooks;gatherTooltipComponents(Lnet/minecraft/world/item/ItemStack;Ljava/util/List;IIILnet/minecraft/client/gui/Font;)Ljava/util/List;", + * remap = false), + * cancellable = true) + * private void mui$replaceWithRichTooltip2(CallbackInfo ci, + * + * @Local(argsOnly = true) Font font, + * + * @Local(argsOnly = true) List tooltipLines, + * + * @Local(ordinal = 0, argsOnly = true) int mouseX, + * + * @Local(ordinal = 1, argsOnly = true) int mouseY) { + * mui$drawRichTooltip(font, tooltipLines, Optional.empty(), mouseX, mouseY, ci); + * } + * + * @Unique + * private void mui$drawRichTooltip(Font font, List textLines, + * Optional tooltipComponent, int mouseX, int mouseY, + * CallbackInfo ci) { + * if (!ModularUIConfig.replaceVanillaTooltips() || textLines.isEmpty()) { + * return; + * } + * + * RichTooltip tooltip = new RichTooltip(); + * tooltip.parent(area -> RichTooltip.findIngredientArea(area, mouseX, mouseY)); + * // Other positions don't really work due to the lack of GuiContext in non-modular uis + * tooltip.add(textLines.getFirst()).newLine(); + * // vanilla inserts the bundle tooltip here so we should do it as the 2nd item too + * tooltipComponent.ifPresent(tooltip::addLine); + * + * if (!this.tooltipStack.isEmpty()) { + * tooltip.spaceLine(); + * } + * for (int i = 1, n = textLines.size(); i < n; i++) { + * tooltip.add(textLines.get(i)).newLine(); + * } + * + * GuiContext context = GuiContext.getDefault(); + * GuiGraphics lastGraphics = context.getGraphics(); + * + * context.setOverrideFont(font); + * context.setGraphics((GuiGraphics) (Object) this); + * tooltip.draw(context, this.tooltipStack); + * + * context.setGraphics(lastGraphics); + * // the override font is removed at the end of RichTooltip#draw; no need to duplicate that here + * + * // Cancel vanilla tooltip rendering + * ci.cancel(); + * } + */ } diff --git a/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java b/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java index 5119ceb8..ca018492 100755 --- a/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/client/MinecraftMixin.java @@ -22,7 +22,9 @@ public class MinecraftMixin { public Screen screen; @Inject(method = "runTick", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/DeltaTracker$Timer;advanceTime(JZ)I", shift = At.Shift.AFTER)) + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/DeltaTracker$Timer;advanceTime(JZ)I", + shift = At.Shift.AFTER)) public void modularui$updateTimer(CallbackInfo ci) { int ticks = ModularUIClient.getTimer60Fps().advanceTime(Util.getMillis(), true); for (int j = 0; j < Math.min(20, ticks); ++j) { @@ -30,7 +32,8 @@ public class MinecraftMixin { } } - @Inject(method = "setScreen", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/Screen;removed()V")) + @Inject(method = "setScreen", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/Screen;removed()V")) public void modularui$trackRealScreenClose(Screen guiScreen, CallbackInfo ci) { if (guiScreen == null) { // the ScreenEvent.Closing is also closed when the screen is transitioning to another screen, diff --git a/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializationMixin.java b/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializationMixin.java index 6e681f72..8aa82793 100644 --- a/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializationMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/common/ComponentSerializationMixin.java @@ -1,15 +1,13 @@ package brachy.modularui.core.mixins.common; import brachy.modularui.drawable.text.ModularComponent; +import brachy.modularui.utils.serialization.codec.CodecUtil; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.ComponentSerialization; -import brachy.modularui.utils.serialization.codec.CodecUtil; - import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; - import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable; diff --git a/src/main/java/brachy/modularui/core/mixins/common/RegistryFriendlyByteBufMixin.java b/src/main/java/brachy/modularui/core/mixins/common/RegistryFriendlyByteBufMixin.java index 5e0de743..20c9065d 100644 --- a/src/main/java/brachy/modularui/core/mixins/common/RegistryFriendlyByteBufMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/common/RegistryFriendlyByteBufMixin.java @@ -8,5 +8,4 @@ // implement IRegistryFriendlyByteBufExtension on RegistryFriendlyByteBuf at runtime @Mixin(RegistryFriendlyByteBuf.class) -public class RegistryFriendlyByteBufMixin implements IRegistryFriendlyByteBufExtension { -} +public class RegistryFriendlyByteBufMixin implements IRegistryFriendlyByteBufExtension {} diff --git a/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java b/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java index bf5109b5..be8c2a5d 100644 --- a/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/common/TextColorMixin.java @@ -12,7 +12,8 @@ public class TextColorMixin { /** * @reason Minecraft uses Integer.parseInt which fails when alpha is specified because of signed vs. unsigned */ - @Redirect(method = "parseColor", at = @At(value = "INVOKE", target = "Ljava/lang/Integer;parseInt(Ljava/lang/String;I)I")) + @Redirect(method = "parseColor", + at = @At(value = "INVOKE", target = "Ljava/lang/Integer;parseInt(Ljava/lang/String;I)I")) private static int fixDecode(String s, int radix) { return (int) Long.parseLong(s, radix); } diff --git a/src/main/java/brachy/modularui/core/mixins/common/WorldLoaderMixin.java b/src/main/java/brachy/modularui/core/mixins/common/WorldLoaderMixin.java index a25a799b..a036bfa3 100644 --- a/src/main/java/brachy/modularui/core/mixins/common/WorldLoaderMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/common/WorldLoaderMixin.java @@ -18,8 +18,8 @@ public class WorldLoaderMixin { @Inject(method = "load", at = @At(value = "INVOKE", - target = "Lnet/minecraft/resources/RegistryDataLoader;load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/core/RegistryAccess;Ljava/util/List;)Lnet/minecraft/core/RegistryAccess$Frozen;", - shift = At.Shift.BEFORE)) + target = "Lnet/minecraft/resources/RegistryDataLoader;load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/core/RegistryAccess;Ljava/util/List;)Lnet/minecraft/core/RegistryAccess$Frozen;", + shift = At.Shift.BEFORE)) private static void mui$captureRegistries1(CallbackInfoReturnable> cir, @Local(ordinal = 0) RegistryAccess.Frozen registriesWithDimensions) { RegistryAccessContainer.update(registriesWithDimensions, null); @@ -27,8 +27,8 @@ public class WorldLoaderMixin { @Inject(method = "load", at = @At(value = "INVOKE_ASSIGN", - target = "Lnet/minecraft/resources/RegistryDataLoader;load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/core/RegistryAccess;Ljava/util/List;)Lnet/minecraft/core/RegistryAccess$Frozen;", - shift = At.Shift.AFTER)) + target = "Lnet/minecraft/resources/RegistryDataLoader;load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/core/RegistryAccess;Ljava/util/List;)Lnet/minecraft/core/RegistryAccess$Frozen;", + shift = At.Shift.AFTER)) private static void mui$captureRegistries2(CallbackInfoReturnable> cir, @Local(ordinal = 1) RegistryAccess.Frozen registriesWithEverything) { RegistryAccessContainer.update(registriesWithEverything, null); diff --git a/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java b/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java index d0cf4827..9b440e04 100644 --- a/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/emi/EmiRenderHelperMixin.java @@ -14,7 +14,8 @@ public class EmiRenderHelperMixin { @Inject(method = "renderRecipe", - at = @At(value = "INVOKE", target = "Ldev/emi/emi/api/recipe/EmiRecipe;addWidgets(Ldev/emi/emi/api/widget/WidgetHolder;)V")) + at = @At(value = "INVOKE", + target = "Ldev/emi/emi/api/recipe/EmiRecipe;addWidgets(Ldev/emi/emi/api/widget/WidgetHolder;)V")) private static void modularui$tellTheRecipeItsInATooltip(EmiRecipe recipe, EmiDrawContext context, int x, int y, boolean showMissing, int overlayColor, CallbackInfo ci) { diff --git a/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java b/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java index 305e043a..0d36a2b3 100644 --- a/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/emi/RecipeScreenMixin.java @@ -16,10 +16,12 @@ @Mixin(value = RecipeScreen.class, remap = false) public class RecipeScreenMixin { - @Shadow private List currentPage; + @Shadow + private List currentPage; @Inject(method = "mouseScrolled", at = @At("HEAD"), remap = true, cancellable = true) - private void modularui$mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY, CallbackInfoReturnable cir) { + private void modularui$mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY, + CallbackInfoReturnable cir) { for (WidgetGroup group : currentPage) { for (Widget widget : group.widgets) { if (widget instanceof ModularUIEmiRecipe.UIWrapperWidget wrapperWidget) { @@ -32,7 +34,8 @@ public class RecipeScreenMixin { } @Inject(method = "mouseReleased", at = @At("HEAD"), remap = true, cancellable = true) - private void modularui$mouseReleased(double mouseX, double mouseY, int button, CallbackInfoReturnable cir) { + private void modularui$mouseReleased(double mouseX, double mouseY, int button, + CallbackInfoReturnable cir) { for (WidgetGroup group : currentPage) { for (Widget widget : group.widgets) { if (widget instanceof ModularUIEmiRecipe.UIWrapperWidget wrapperWidget) { @@ -45,7 +48,8 @@ public class RecipeScreenMixin { } @Inject(method = "mouseDragged", at = @At("HEAD"), remap = true, cancellable = true) - private void modularui$mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY, CallbackInfoReturnable cir) { + private void modularui$mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY, + CallbackInfoReturnable cir) { for (WidgetGroup group : currentPage) { for (Widget widget : group.widgets) { if (widget instanceof ModularUIEmiRecipe.UIWrapperWidget wrapperWidget) { @@ -56,5 +60,4 @@ public class RecipeScreenMixin { } } } - } diff --git a/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java b/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java index f1fe8357..3f72b280 100644 --- a/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/jei/RecipeGuiLogicMixin.java @@ -2,13 +2,12 @@ import brachy.modularui.integration.jei.recipe.ModularUIJeiCategory; +import net.minecraft.client.renderer.Rect2i; + import mezz.jei.api.gui.IRecipeLayoutDrawable; import mezz.jei.common.util.ImmutableSize2i; import mezz.jei.gui.recipes.IRecipeLayoutWithButtons; import mezz.jei.gui.recipes.RecipeGuiLogic; - -import net.minecraft.client.renderer.Rect2i; - import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @@ -19,7 +18,8 @@ public class RecipeGuiLogicMixin { @ModifyArg(method = "getVisibleRecipeLayoutsWithButtons", - at = @At(value = "INVOKE", target = "Ljava/util/Optional;map(Ljava/util/function/Function;)Ljava/util/Optional;")) + at = @At(value = "INVOKE", + target = "Ljava/util/Optional;map(Ljava/util/function/Function;)Ljava/util/Optional;")) private Function, ImmutableSize2i> modularui$useCategoryMaxHeightForLayout(Function, ImmutableSize2i> original) { return layoutWithButtons -> { ImmutableSize2i size = original.apply(layoutWithButtons); @@ -30,7 +30,8 @@ public class RecipeGuiLogicMixin { int borderWidth = size.width() - area.getWidth(); // size.height() contains the layout's areaWithBorder.height int borderHeight = size.height() - area.getHeight(); - return new ImmutableSize2i(muiCategory.getMaxWidth() + borderWidth, muiCategory.getMaxHeight() + borderHeight); + return new ImmutableSize2i(muiCategory.getMaxWidth() + borderWidth, + muiCategory.getMaxHeight() + borderHeight); } return size; }; diff --git a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java index 03269f8d..0c5244a3 100644 --- a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutBuilderMixin.java @@ -48,7 +48,9 @@ public abstract class RecipeLayoutBuilderMixin implements IRecipeLayoutBuilde @SuppressWarnings({ "rawtypes", "unchecked" }) @ModifyExpressionValue(method = { "createShapelessIcon", "getRecipeTransferButtonPosition" }, - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), require = 0) + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), + require = 0) private static int modularui$makeWidthRecipeDependent(int original, @Local(argsOnly = true) IRecipeCategory recipeCategory) { if (recipeCategory instanceof ModularUIJeiCategory muiCategory) { @@ -59,7 +61,9 @@ public abstract class RecipeLayoutBuilderMixin implements IRecipeLayoutBuilde @SuppressWarnings({ "rawtypes", "unchecked" }) @ModifyExpressionValue(method = { "createShapelessIcon", "getRecipeTransferButtonPosition" }, - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), require = 0) + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), + require = 0) private static int modularui$makeHeightRecipeDependent(int original, @Local(argsOnly = true) IRecipeCategory recipeCategory) { if (recipeCategory instanceof ModularUIJeiCategory muiCategory) { diff --git a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java index 28c3f603..00322384 100644 --- a/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/jei/RecipeLayoutMixin.java @@ -10,7 +10,6 @@ import mezz.jei.api.gui.inputs.RecipeSlotUnderMouse; import mezz.jei.api.recipe.category.IRecipeCategory; import mezz.jei.library.gui.recipes.RecipeLayout; - import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -26,8 +25,10 @@ public abstract class RecipeLayoutMixin implements IRecipeLayoutDrawable { private @Final IRecipeCategory recipeCategory; @WrapOperation(method = "drawOverlays", - at = @At(value = "INVOKE", target = "Lmezz/jei/library/gui/recipes/RecipeLayout;getSlotUnderMouse(DD)Ljava/util/Optional;")) - private Optional modularui$disableIngredientTooltipRender(RecipeLayout self, double mouseX, double mouseY, + at = @At(value = "INVOKE", + target = "Lmezz/jei/library/gui/recipes/RecipeLayout;getSlotUnderMouse(DD)Ljava/util/Optional;")) + private Optional modularui$disableIngredientTooltipRender(RecipeLayout self, double mouseX, + double mouseY, Operation> original) { if (self.getRecipeCategory() instanceof ModularUIJeiCategory) { return Optional.empty(); @@ -36,7 +37,8 @@ public abstract class RecipeLayoutMixin implements IRecipeLayoutDrawable { } @ModifyExpressionValue(method = "", - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getWidth()I"), require = 0) private int modularui$makeWidthRecipeDependent(int original, @Local(argsOnly = true) R recipe) { @@ -47,7 +49,8 @@ public abstract class RecipeLayoutMixin implements IRecipeLayoutDrawable { } @ModifyExpressionValue(method = "", - at = @At(value = "INVOKE", target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), + at = @At(value = "INVOKE", + target = "Lmezz/jei/api/recipe/category/IRecipeCategory;getHeight()I"), require = 0) private int modularui$makeHeightRecipeDependent(int original, @Local(argsOnly = true) R recipe) { diff --git a/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java b/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java index b684d8a7..3d8174dc 100644 --- a/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java +++ b/src/main/java/brachy/modularui/core/mixins/rei/DefaultDisplayViewingScreenMixin.java @@ -1,7 +1,7 @@ package brachy.modularui.core.mixins.rei; -import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; import brachy.modularui.integration.rei.recipe.ModularUIReiCategory; +import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; @@ -34,7 +34,9 @@ protected DefaultDisplayViewingScreenMixin(Map, List category, Operation original, @Local(name = "display") Display display) { @@ -42,7 +44,8 @@ protected DefaultDisplayViewingScreenMixin(Map, List displaySupplier) { @@ -53,7 +56,8 @@ protected DefaultDisplayViewingScreenMixin(Map, List category, Display display, @Nullable ToIntFunction> originalValue) { - if (category instanceof ModularUIReiCategory muiCategory && display instanceof ModularUIReiDisplay muiDisplay) { + if (category instanceof ModularUIReiCategory muiCategory && + display instanceof ModularUIReiDisplay muiDisplay) { return ((ModularUIReiCategory) muiCategory).getDisplayHeight(muiDisplay); } else { // if this isn't a MUI display, set it back to the original value diff --git a/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java b/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java index 495f1187..20f5ec81 100644 --- a/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java +++ b/src/main/java/brachy/modularui/core/mixins/rei/EntryWidgetAccessor.java @@ -1,9 +1,8 @@ package brachy.modularui.core.mixins.rei; -import me.shedaniel.rei.impl.client.gui.widget.EntryWidget; - import net.minecraft.client.gui.GuiGraphics; +import me.shedaniel.rei.impl.client.gui.widget.EntryWidget; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; diff --git a/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java b/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java index 153670fd..ecc61f17 100644 --- a/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java +++ b/src/main/java/brachy/modularui/drawable/AdaptableUITexture.java @@ -4,8 +4,8 @@ import net.minecraft.client.renderer.GameRenderer; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import lombok.experimental.Accessors; import org.joml.Matrix4f; @@ -19,14 +19,18 @@ @Accessors(fluent = true) public class AdaptableUITexture extends UITexture { - @Getter private final int imageWidth, imageHeight, bl, bt, br, bb; - @Getter private final boolean tiled; + @Getter + private final int imageWidth, imageHeight, bl, bt, br, bb; + @Getter + private final boolean tiled; /** * Use {@link UITexture#builder()} with {@link Builder#adaptable(int, int)} */ - AdaptableUITexture(ResourceLocation location, float u0, float v0, float u1, float v1, ColorType colorType, boolean nonOpaque, - int colorOverride, int imageWidth, int imageHeight, int bl, int bt, int br, int bb, boolean tiled) { + AdaptableUITexture(ResourceLocation location, float u0, float v0, float u1, float v1, ColorType colorType, + boolean nonOpaque, + int colorOverride, int imageWidth, int imageHeight, int bl, int bt, int br, int bb, + boolean tiled) { super(location, u0, v0, u1, v1, colorType, nonOpaque, colorOverride); this.imageWidth = imageWidth; this.imageHeight = imageHeight; @@ -45,7 +49,8 @@ public AdaptableUITexture register(String name) { @Override public AdaptableUITexture getSubArea(float uStart, float vStart, float uEnd, float vEnd) { return new AdaptableUITexture(this.location, lerpU(uStart), lerpV(vStart), lerpU(uEnd), lerpV(vEnd), - this.colorType, this.nonOpaque, this.colorOverride, this.imageWidth, this.imageHeight, this.bl, this.bt, this.br, this.bb, + this.colorType, this.nonOpaque, this.colorOverride, this.imageWidth, this.imageHeight, this.bl, this.bt, + this.br, this.bb, this.tiled); } @@ -154,9 +159,11 @@ public void drawTiled(GuiContext context, float x, float y, float width, float h if ((this.bl > 0 || this.br > 0) && this.bt <= 0 && this.bb <= 0) { // left border - GuiDraw.drawTiledTexture(pose, x, y, this.bl, height, this.u0, this.v0, uInnerStart, this.v1, this.bl, th, 0); + GuiDraw.drawTiledTexture(pose, x, y, this.bl, height, this.u0, this.v0, uInnerStart, this.v1, this.bl, th, + 0); // right border - GuiDraw.drawTiledTexture(pose, x1 - this.br, y, this.br, height, uInnerEnd, this.v0, this.u1, this.v1, this.br, th, 0); + GuiDraw.drawTiledTexture(pose, x1 - this.br, y, this.br, height, uInnerEnd, this.v0, this.u1, this.v1, + this.br, th, 0); // center GuiDraw.drawTiledTexture(pose, x + this.bl, y, width - this.bl - this.br, height, uInnerStart, this.v0, uInnerEnd, this.v1, tw - this.bl - this.br, th, 0); diff --git a/src/main/java/brachy/modularui/drawable/Circle.java b/src/main/java/brachy/modularui/drawable/Circle.java index bb7d2f92..c8bb5fcb 100644 --- a/src/main/java/brachy/modularui/drawable/Circle.java +++ b/src/main/java/brachy/modularui/drawable/Circle.java @@ -8,10 +8,10 @@ import brachy.modularui.utils.Interpolations; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.mojang.serialization.Codec; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.ToString; diff --git a/src/main/java/brachy/modularui/drawable/ColorType.java b/src/main/java/brachy/modularui/drawable/ColorType.java index 606ccefa..97b9b8d2 100755 --- a/src/main/java/brachy/modularui/drawable/ColorType.java +++ b/src/main/java/brachy/modularui/drawable/ColorType.java @@ -2,9 +2,7 @@ import brachy.modularui.theme.WidgetTheme; -import net.minecraft.util.ExtraCodecs; import com.mojang.serialization.Codec; - import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.Getter; diff --git a/src/main/java/brachy/modularui/drawable/CycleDrawable.java b/src/main/java/brachy/modularui/drawable/CycleDrawable.java index 2df9576e..8355996b 100644 --- a/src/main/java/brachy/modularui/drawable/CycleDrawable.java +++ b/src/main/java/brachy/modularui/drawable/CycleDrawable.java @@ -5,9 +5,8 @@ import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.mojang.serialization.Codec; - import com.google.common.collect.Iterables; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -22,7 +21,8 @@ public class CycleDrawable implements IDrawable { public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(CycleDrawable::new) - .addOpt("drawables", CycleDrawable::drawables, CycleDrawable::getListDrawables, IDrawable.CODEC.listOf(), Collections.emptyList()) + .addOpt("drawables", CycleDrawable::drawables, CycleDrawable::getListDrawables, IDrawable.CODEC.listOf(), + Collections.emptyList()) .addOpt("cycleTime", CycleDrawable::cycleTime, CycleDrawable::cycleTime, Codec.INT, 1000) .build(); diff --git a/src/main/java/brachy/modularui/drawable/DrawableStack.java b/src/main/java/brachy/modularui/drawable/DrawableStack.java index 2bd67972..318121dd 100644 --- a/src/main/java/brachy/modularui/drawable/DrawableStack.java +++ b/src/main/java/brachy/modularui/drawable/DrawableStack.java @@ -5,11 +5,11 @@ import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.serialization.codec.CodecUtil; -import net.minecraft.util.ExtraCodecs; -import com.mojang.serialization.Codec; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; + import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -19,9 +19,9 @@ */ public record DrawableStack(IDrawable... drawables) implements IDrawable { - public static final Codec CODEC = Codec.lazyInitialized(() -> - CodecUtil.checkedEncoder(IDrawable.CODEC.listOf().xmap(DrawableStack::fromList, DrawableStack::toList), - d -> d instanceof DrawableStack)); + public static final Codec CODEC = Codec.lazyInitialized(() -> CodecUtil.checkedEncoder( + IDrawable.CODEC.listOf().xmap(DrawableStack::fromList, DrawableStack::toList), + d -> d instanceof DrawableStack)); public static final IDrawable[] EMPTY_BACKGROUND = {}; public static final DrawableStack EMPTY = new DrawableStack(EMPTY_BACKGROUND); diff --git a/src/main/java/brachy/modularui/drawable/FluidDrawable.java b/src/main/java/brachy/modularui/drawable/FluidDrawable.java index 0661875d..981bd049 100644 --- a/src/main/java/brachy/modularui/drawable/FluidDrawable.java +++ b/src/main/java/brachy/modularui/drawable/FluidDrawable.java @@ -9,17 +9,15 @@ import net.minecraft.Util; import net.minecraft.core.component.DataComponentPatch; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.material.Fluid; -import com.mojang.serialization.Codec; import net.neoforged.neoforge.fluids.FluidStack; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; import org.apache.commons.lang3.ArrayUtils; -import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collection; @@ -30,7 +28,8 @@ public class FluidDrawable implements IDrawable { public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(FluidDrawable::new) - .add("fluids", FluidDrawable::fluids, FluidDrawable::getFluidList, CodecUtil.listLike(FluidStack.CODEC)).alias("fluid") + .add("fluids", FluidDrawable::fluids, FluidDrawable::getFluidList, CodecUtil.listLike(FluidStack.CODEC)) + .alias("fluid") .addOpt("cycleTime", FluidDrawable::cycleTime, FluidDrawable::cycleTime, Codec.INT, 1000) .build(); diff --git a/src/main/java/brachy/modularui/drawable/GuiDraw.java b/src/main/java/brachy/modularui/drawable/GuiDraw.java index a7578760..03d94a3c 100644 --- a/src/main/java/brachy/modularui/drawable/GuiDraw.java +++ b/src/main/java/brachy/modularui/drawable/GuiDraw.java @@ -30,6 +30,13 @@ import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.event.RenderTooltipEvent; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.fluids.FluidStack; + import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; @@ -39,13 +46,6 @@ import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import net.neoforged.neoforge.client.event.RenderTooltipEvent; -import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; -import net.neoforged.neoforge.common.NeoForge; -import net.neoforged.neoforge.fluids.FluidStack; - import org.jetbrains.annotations.Nullable; import org.joml.Matrix4d; import org.joml.Matrix4f; @@ -86,13 +86,17 @@ public static void drawRect(GuiGraphics graphics, float x0, float y0, float w, f float x1 = x0 + w, y1 = y0 + h; buffer.addVertex(pose, x0, y0, 0.0f) - .setColor(Color.getRed(colorTL), Color.getGreen(colorTL), Color.getBlue(colorTL), Color.getAlpha(colorTL)); + .setColor(Color.getRed(colorTL), Color.getGreen(colorTL), Color.getBlue(colorTL), + Color.getAlpha(colorTL)); buffer.addVertex(pose, x0, y1, 0.0f) - .setColor(Color.getRed(colorBL), Color.getGreen(colorBL), Color.getBlue(colorBL), Color.getAlpha(colorBL)); + .setColor(Color.getRed(colorBL), Color.getGreen(colorBL), Color.getBlue(colorBL), + Color.getAlpha(colorBL)); buffer.addVertex(pose, x1, y1, 0.0f) - .setColor(Color.getRed(colorBR), Color.getGreen(colorBR), Color.getBlue(colorBR), Color.getAlpha(colorBR)); + .setColor(Color.getRed(colorBR), Color.getGreen(colorBR), Color.getBlue(colorBR), + Color.getAlpha(colorBR)); buffer.addVertex(pose, x1, y0, 0.0f) - .setColor(Color.getRed(colorTR), Color.getGreen(colorTR), Color.getBlue(colorTR), Color.getAlpha(colorTR)); + .setColor(Color.getRed(colorTR), Color.getGreen(colorTR), Color.getBlue(colorTR), + Color.getAlpha(colorTR)); } public static void drawRectRaw(VertexConsumer buffer, Matrix4f pose, float x0, float y0, float x1, float y1, @@ -159,7 +163,8 @@ public static void drawVerticalGradientRoundedRect(GuiGraphics graphics, float x } public static void drawHorizontalGradientRoundedRect(GuiGraphics graphics, float x0, float y0, float w, float h, - int colorLeft, int colorRight, int cornerRadius, int segments) { + int colorLeft, int colorRight, int cornerRadius, + int segments) { drawRoundedRect(graphics, x0, y0, w, h, colorLeft, colorRight, colorLeft, colorRight, cornerRadius, segments); } @@ -213,7 +218,8 @@ public static void drawRoundedRect(GuiGraphics graphics, float x0, float y0, flo /** * Set up the texture as a sampler differently depending on if it's part of the GUI atlas or not. *

- * If the texture is part of the GUI atlas, the atlas will be used for drawing and the UV coordinates will be scaled to the atlas texture.
+ * If the texture is part of the GUI atlas, the atlas will be used for drawing and the UV coordinates will be scaled + * to the atlas texture.
* If it's not part of the GUI atlas, nothing special is done. * * @param location the texture file's location, e.g. {@code "modularui:textures/gui/slot/item.png"} @@ -222,7 +228,7 @@ public static void drawRoundedRect(GuiGraphics graphics, float x0, float y0, flo * @param u1 u1 UV coordinate * @param v1 v1 UV coordinate * @return If texture is in the GUI atlas, rescaled UV coordinates {@code u0, v0, u1, v1}.
- * If not, the same coordinates that were passed in. + * If not, the same coordinates that were passed in. */ public static RectangleF setupTexture(ResourceLocation location, float u0, float v0, float u1, float v1) { TextureAtlasSprite sprite = Minecraft.getInstance().getGuiSprites() @@ -241,7 +247,8 @@ public static RectangleF setupTexture(ResourceLocation location, float u0, float public static boolean isGuiAtlasSprite(ResourceLocation location) { location = GUI_TEXTURE_ID_CONVERTER.fileToId(location); - return GuiSpriteManager.getInstance().getSprite(location).atlasLocation() != MissingTextureAtlasSprite.getLocation(); + return GuiSpriteManager.getInstance().getSprite(location).atlasLocation() != + MissingTextureAtlasSprite.getLocation(); } public static void drawTexture(Matrix4f pose, ResourceLocation location, float x, float y, float w, float h, @@ -354,7 +361,8 @@ public static void drawTexture(Matrix4f pose, VertexConsumer buffer, float x0, f } public static void drawTiledTexture(Matrix4f pose, ResourceLocation location, float x, float y, float w, float h, - int u, int v, int tileWidth, int tileHeight, int textureWidth, int textureHeight, float z) { + int u, int v, int tileWidth, int tileHeight, int textureWidth, + int textureHeight, float z) { if (!isGuiAtlasSprite(location)) { RenderSystem.setShaderTexture(0, location); drawTiledTexture(pose, x, y, w, h, u, v, tileWidth, tileHeight, textureWidth, textureHeight, z); @@ -401,7 +409,8 @@ public static void drawTiledTexture(Matrix4f pose, ResourceLocation location, fl RectangleF newUvs = setupTexture(location, u0, v0, u1, v1); - drawTiledTexture(pose, x, y, w, h, newUvs.u0(), newUvs.v0(), newUvs.u1(), newUvs.v1(), textureWidth, textureHeight, z); + drawTiledTexture(pose, x, y, w, h, newUvs.u0(), newUvs.v0(), newUvs.u1(), newUvs.v1(), textureWidth, + textureHeight, z); RenderSystem.disableBlend(); } @@ -659,7 +668,8 @@ public static void drawFluidTexture(GuiGraphics graphics, FluidStack content, public static void drawStandardSlotAmountText(GuiContext context, int amount, String format, Area area, float z) { - drawAmountText(context.getMuiContext(), amount, format, 0, 0, area.width, area.height, Alignment.BottomRight, z); + drawAmountText(context.getMuiContext(), amount, format, 0, 0, area.width, area.height, Alignment.BottomRight, + z); } public static void drawAmountText(ModularGuiContext context, int amount, String format, @@ -994,7 +1004,8 @@ public static void drawText(GuiGraphics graphics, FormattedCharSequence text, fl @SuppressWarnings("UnstableApiUsage") public static void drawTooltipBackground(GuiContext context, ItemStack stack, List lines, - int x, int y, int textWidth, int height, @Nullable IRichTextBuilder tooltip) { + int x, int y, int textWidth, int height, + @Nullable IRichTextBuilder tooltip) { GuiGraphics graphics = context.getGraphics(); // TODO theme color diff --git a/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java b/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java index 5be6ba16..41827b48 100644 --- a/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java +++ b/src/main/java/brachy/modularui/drawable/GuiSpriteManager.java @@ -13,7 +13,8 @@ * 1.21 has this class in vanilla, it can be used via {@code Minecraft.getGuiSprites()}.
* Here in 1.20 land, though, we have to implement it ourselves. *

- * Note that the atlas JSON should be kept, as MC 1.21 only adds textures in gui/sprites to the atlas. We want all of them. + * Note that the atlas JSON should be kept, as MC 1.21 only adds textures in gui/sprites to the atlas. We want + * all of them. */ public class GuiSpriteManager extends TextureAtlasHolder { @@ -45,5 +46,4 @@ public static GuiSpriteManager getInstance() { public @NotNull TextureAtlasSprite getSprite(@NotNull ResourceLocation location) { return super.getSprite(location); } - } diff --git a/src/main/java/brachy/modularui/drawable/GuiTextures.java b/src/main/java/brachy/modularui/drawable/GuiTextures.java index fde66650..a31ab1d4 100644 --- a/src/main/java/brachy/modularui/drawable/GuiTextures.java +++ b/src/main/java/brachy/modularui/drawable/GuiTextures.java @@ -205,8 +205,12 @@ public interface GuiTextures { UITexture ANIMATED_TEXTURE_TEST = UITexture.fullImage(ModularUI.id("gui/icons/animated_gradient")); - TabTexture TAB_TOP = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_top"), ColorType.DEFAULT), GuiAxis.Y, false, 28, 32, 4); - TabTexture TAB_BOTTOM = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_bottom"), ColorType.DEFAULT), GuiAxis.Y, true, 28, 32, 4); - TabTexture TAB_LEFT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_left"), ColorType.DEFAULT), GuiAxis.X, false, 32, 28, 4); - TabTexture TAB_RIGHT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_right"), ColorType.DEFAULT), GuiAxis.X, true, 32, 28, 4); + TabTexture TAB_TOP = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_top"), ColorType.DEFAULT), + GuiAxis.Y, false, 28, 32, 4); + TabTexture TAB_BOTTOM = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_bottom"), ColorType.DEFAULT), + GuiAxis.Y, true, 28, 32, 4); + TabTexture TAB_LEFT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_left"), ColorType.DEFAULT), + GuiAxis.X, false, 32, 28, 4); + TabTexture TAB_RIGHT = TabTexture.of(UITexture.fullImage(ModularUI.id("gui/tab/tabs_right"), ColorType.DEFAULT), + GuiAxis.X, true, 32, 28, 4); } diff --git a/src/main/java/brachy/modularui/drawable/Icon.java b/src/main/java/brachy/modularui/drawable/Icon.java index a938d649..87959fe1 100644 --- a/src/main/java/brachy/modularui/drawable/Icon.java +++ b/src/main/java/brachy/modularui/drawable/Icon.java @@ -9,10 +9,10 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import brachy.modularui.widget.sizer.Box; -import com.mojang.serialization.Codec; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; import lombok.Getter; /** @@ -29,11 +29,16 @@ public class Icon implements IIcon { .addOpt("margin", Icon::margin, Icon::getMargin, Box.CODEC, Box.ZERO) .build(); - @Getter private IDrawable drawable; - @Getter private int width = 0, height = 0; - @Getter private float aspectRatio = 0; - @Getter private Alignment alignment = Alignment.Center; - @Getter private final Box margin = new Box(); + @Getter + private IDrawable drawable; + @Getter + private int width = 0, height = 0; + @Getter + private float aspectRatio = 0; + @Getter + private Alignment alignment = Alignment.Center; + @Getter + private final Box margin = new Box(); private Icon() { this.drawable = IDrawable.EMPTY; diff --git a/src/main/java/brachy/modularui/drawable/InteractableIcon.java b/src/main/java/brachy/modularui/drawable/InteractableIcon.java index 6d3d4b95..3977a922 100644 --- a/src/main/java/brachy/modularui/drawable/InteractableIcon.java +++ b/src/main/java/brachy/modularui/drawable/InteractableIcon.java @@ -3,7 +3,6 @@ import brachy.modularui.api.drawable.IIcon; import brachy.modularui.api.widget.IGuiAction; import brachy.modularui.api.widget.Interactable; - import brachy.modularui.screen.viewport.GuiContext; import lombok.Getter; diff --git a/src/main/java/brachy/modularui/drawable/ItemDrawable.java b/src/main/java/brachy/modularui/drawable/ItemDrawable.java index f04a8c3b..c039cb17 100755 --- a/src/main/java/brachy/modularui/drawable/ItemDrawable.java +++ b/src/main/java/brachy/modularui/drawable/ItemDrawable.java @@ -11,16 +11,13 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.ItemLike; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import com.google.gson.JsonObject; - import com.google.gson.JsonParseException; - import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; - import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -36,7 +33,8 @@ public class ItemDrawable implements IDrawable { public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(ItemDrawable::new) - .add("items", ItemDrawable::items, ItemDrawable::getItemList, CodecUtil.listLike(ItemStack.CODEC)).alias("item") + .add("items", ItemDrawable::items, ItemDrawable::getItemList, CodecUtil.listLike(ItemStack.CODEC)) + .alias("item") .addOpt("cycleTime", ItemDrawable::cycleTime, ItemDrawable::cycleTime, Codec.INT, 1000) .build(); diff --git a/src/main/java/brachy/modularui/drawable/Rectangle.java b/src/main/java/brachy/modularui/drawable/Rectangle.java index 7cdd6ef2..24a8cb16 100644 --- a/src/main/java/brachy/modularui/drawable/Rectangle.java +++ b/src/main/java/brachy/modularui/drawable/Rectangle.java @@ -1,6 +1,5 @@ package brachy.modularui.drawable; -import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.ModularUI; import brachy.modularui.animation.IAnimatable; import brachy.modularui.api.drawable.IDrawable; @@ -8,13 +7,14 @@ import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.Color; import brachy.modularui.utils.Interpolations; +import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.utils.serialization.codec.MutableObjectCodec; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.serialization.Codec; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -177,8 +177,10 @@ public final boolean equals(Object o) { if (!(o instanceof Rectangle rectangle)) return false; return cornerRadius == rectangle.cornerRadius && colorTL == rectangle.colorTL && colorTR == rectangle.colorTR && - colorBL == rectangle.colorBL && colorBR == rectangle.colorBR && cornerSegments == rectangle.cornerSegments && - Float.compare(borderThickness, rectangle.borderThickness) == 0 && canApplyTheme == rectangle.canApplyTheme; + colorBL == rectangle.colorBL && colorBR == rectangle.colorBR && + cornerSegments == rectangle.cornerSegments && + Float.compare(borderThickness, rectangle.borderThickness) == 0 && + canApplyTheme == rectangle.canApplyTheme; } @Override diff --git a/src/main/java/brachy/modularui/drawable/SchemaRenderer.java b/src/main/java/brachy/modularui/drawable/SchemaRenderer.java index 0afa5477..6e8a67e7 100755 --- a/src/main/java/brachy/modularui/drawable/SchemaRenderer.java +++ b/src/main/java/brachy/modularui/drawable/SchemaRenderer.java @@ -6,8 +6,8 @@ import brachy.modularui.drawable.schema.ISchema; import net.minecraft.world.phys.BlockHitResult; -import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.PoseStack; import lombok.Setter; import lombok.experimental.Accessors; import lombok.experimental.Tolerate; diff --git a/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java b/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java index 5eb860a8..2da991e8 100644 --- a/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java +++ b/src/main/java/brachy/modularui/drawable/SubAreaDrawable.java @@ -7,14 +7,15 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import net.minecraft.util.Mth; -import com.mojang.serialization.Codec; +import com.mojang.serialization.Codec; import lombok.Getter; import org.jetbrains.annotations.Nullable; public class SubAreaDrawable extends DelegateDrawable { - public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(SubAreaDrawable::new) + public static final MutableObjectCodec CODEC = MutableObjectCodec + .drawableBuilder(SubAreaDrawable::new) .add("drawable", SubAreaDrawable::drawable, SubAreaDrawable::getWrappedDrawable, IDrawable.CODEC) .addOpt("u0", SubAreaDrawable::u0, SubAreaDrawable::getU0, Codec.FLOAT, 0f).alias("uStart") .addOpt("v0", SubAreaDrawable::v0, SubAreaDrawable::getV0, Codec.FLOAT, 0f).alias("vStart") @@ -35,7 +36,8 @@ public SubAreaDrawable(@Nullable IDrawable drawable) { @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { - context.getStencil().push(x + this.u0 * width, y + this.v0 * height, (this.u1 - this.u0) * width, (this.v1 - this.v0) * height); + context.getStencil().push(x + this.u0 * width, y + this.v0 * height, (this.u1 - this.u0) * width, + (this.v1 - this.v0) * height); super.draw(context, x, y, width, height, widgetTheme); context.getStencil().pop(); } diff --git a/src/main/java/brachy/modularui/drawable/TextureRegistry.java b/src/main/java/brachy/modularui/drawable/TextureRegistry.java index 5762a6dc..264a6c12 100644 --- a/src/main/java/brachy/modularui/drawable/TextureRegistry.java +++ b/src/main/java/brachy/modularui/drawable/TextureRegistry.java @@ -18,7 +18,9 @@ private static synchronized void registerTextureInternal(String name, UITexture UITexture current = TEXTURES.put(name, texture); REVERSE_TEXTURES.put(texture, name); if (current != null && (ModularUI.isDev() || ModularUIConfig.Dev.debugUI())) { - ModularUI.LOGGER.warn("[DEBUG] Replacing texture with name '{}' and location '{}' with texture with location '{}'", name, current.location, texture.location); + ModularUI.LOGGER.warn( + "[DEBUG] Replacing texture with name '{}' and location '{}' with texture with location '{}'", name, + current.location, texture.location); } } @@ -52,9 +54,12 @@ public static void registerTextureAutoName(UITexture texture) { number++; name = baseName + "_" + number; if (number == 20 && (ModularUI.isDev() || ModularUIConfig.Dev.debugUI())) { - ModularUI.LOGGER.warn("[DEBUG] Trying to register a UITexture with location '{}' for at least 20 times. This is likely a bug and should be fixed.", texture.location); + ModularUI.LOGGER.warn( + "[DEBUG] Trying to register a UITexture with location '{}' for at least 20 times. This is likely a bug and should be fixed.", + texture.location); } else if (number == 10000) { - throw new IllegalStateException("Trying to register a UITexture with location '" + texture.location + "' 10000 times."); + throw new IllegalStateException( + "Trying to register a UITexture with location '" + texture.location + "' 10000 times."); } } registerTexture(name, texture); diff --git a/src/main/java/brachy/modularui/drawable/TiledUITexture.java b/src/main/java/brachy/modularui/drawable/TiledUITexture.java index 55a0ae7a..db04aab6 100644 --- a/src/main/java/brachy/modularui/drawable/TiledUITexture.java +++ b/src/main/java/brachy/modularui/drawable/TiledUITexture.java @@ -4,8 +4,8 @@ import net.minecraft.client.renderer.GameRenderer; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import lombok.experimental.Accessors; @@ -14,7 +14,8 @@ @Accessors(fluent = true) public class TiledUITexture extends UITexture { - @Getter private final int imageWidth, imageHeight; + @Getter + private final int imageWidth, imageHeight; /** * Use {@link UITexture#builder()} with {@link Builder#tiled()} @@ -45,7 +46,8 @@ public void draw(GuiContext context, float x, float y, float width, float height @Override protected TiledUITexture copy() { - return new TiledUITexture(location, u0, v0, u1, v1, colorType, nonOpaque, colorOverride, imageWidth, imageHeight); + return new TiledUITexture(location, u0, v0, u1, v1, colorType, nonOpaque, colorOverride, imageWidth, + imageHeight); } @Override diff --git a/src/main/java/brachy/modularui/drawable/UITexture.java b/src/main/java/brachy/modularui/drawable/UITexture.java index 55f694e8..ad4e951d 100644 --- a/src/main/java/brachy/modularui/drawable/UITexture.java +++ b/src/main/java/brachy/modularui/drawable/UITexture.java @@ -11,18 +11,16 @@ import net.minecraft.resources.FileToIdConverter; import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.ExtraCodecs; -import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.MapCodec; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.MapCodec; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; -import lombok.experimental.Tolerate; import org.jetbrains.annotations.Nullable; import java.util.Objects; @@ -31,12 +29,15 @@ @Accessors(fluent = true, chain = true) public class UITexture implements IDrawable { - public static final MapCodec CODEC_FROM_BUILDER = Builder.CODEC.flatXmap(Builder::buildForCodec, t -> DataResult.success(t.toBuilder())); - public static final Codec CODEC_FROM_NAME = Codec.stringResolver(TextureRegistry::getTextureId, TextureRegistry::getTexture); + public static final MapCodec CODEC_FROM_BUILDER = Builder.CODEC.flatXmap(Builder::buildForCodec, + t -> DataResult.success(t.toBuilder())); + public static final Codec CODEC_FROM_NAME = Codec.stringResolver(TextureRegistry::getTextureId, + TextureRegistry::getTexture); public static final MapCodec CODEC = IDrawable.CODECS.register("texture", CodecUtil.chainedMapCodec(CODEC_FROM_NAME.fieldOf("name"), CODEC_FROM_BUILDER)); - public static final UITexture DEFAULT = fullImage(ResourceLocation.withDefaultNamespace("gui/options_background"), ColorType.DEFAULT); + public static final UITexture DEFAULT = fullImage(ResourceLocation.withDefaultNamespace("gui/options_background"), + ColorType.DEFAULT); public static final FileToIdConverter GUI_TEXTURE_ID_CONVERTER = new FileToIdConverter("textures/gui", ".png"); private static final ResourceLocation ICONS_LOCATION = ModularUI.id("textures/gui/icons.png"); @@ -62,13 +63,16 @@ static UITexture icon(String name, int x, int y) { @ToString.Include @Getter public final ResourceLocation location; - @Getter public final float u0, v0, u1, v1; + @Getter + public final float u0, v0, u1, v1; @Getter @Nullable public final ColorType colorType; - @Getter public final boolean nonOpaque; + @Getter + public final boolean nonOpaque; - @Getter protected int colorOverride = 0; + @Getter + protected int colorOverride = 0; /** * Creates a drawable texture @@ -95,7 +99,8 @@ public UITexture(ResourceLocation location, float u0, float v0, float u1, float * @param colorType a function to get which color from a widget theme should be used to color this texture. * @param nonOpaque whether the texture should draw with blend (if true) or not (if false) */ - public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, boolean nonOpaque) { + public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, + boolean nonOpaque) { this(location, u0, v0, u1, v1, colorType, nonOpaque, 0); } @@ -107,11 +112,13 @@ public UITexture(ResourceLocation location, float u0, float v0, float u1, float * @param v0 y offset of the image (0-1) * @param u1 x end offset of the image (0-1) * @param v1 y end offset of the image (0-1) - * @param colorType a function to get which color from a widget theme should be used to color this texture. Can be null. + * @param colorType a function to get which color from a widget theme should be used to color this texture. Can + * be null. * @param nonOpaque whether the texture should draw with blend (if true) or not (if false). * @param colorOverride color override for the texture in ARGB format. 0 means no override */ - public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, boolean nonOpaque, int colorOverride) { + public UITexture(ResourceLocation location, float u0, float v0, float u1, float v1, @Nullable ColorType colorType, + boolean nonOpaque, int colorOverride) { this.colorType = colorType; boolean png = !location.getPath().endsWith(PNG_SUFFIX); boolean textures = !location.getPath().startsWith(TEXTURES_PREFIX); @@ -237,7 +244,8 @@ public int hashCode() { } protected UITexture copy() { - return new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque, this.colorOverride); + return new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque, + this.colorOverride); } public UITexture withColorOverride(int color) { @@ -275,19 +283,29 @@ public static class Builder { .addOpt("colorOverride", Builder::colorOverride, Builder::getColorOverride, Codec.INT, 0) .build(); - @Getter private ResourceLocation location; + @Getter + private ResourceLocation location; @Getter @Setter private int iw = -1, ih = -1; - @Getter private int x, y, w, h; - @Getter private float u0 = 0, v0 = 0, u1 = 1, v1 = 1; - @Getter private Mode mode = Mode.FULL; - @Getter private int bl = 0, bt = 0, br = 0, bb = 0; - @Getter private String name; - @Getter private boolean tiled = false; - @Getter private ColorType colorType = null; - @Getter private boolean nonOpaque = false; - @Getter private int colorOverride = 0; + @Getter + private int x, y, w, h; + @Getter + private float u0 = 0, v0 = 0, u1 = 1, v1 = 1; + @Getter + private Mode mode = Mode.FULL; + @Getter + private int bl = 0, bt = 0, br = 0, bb = 0; + @Getter + private String name; + @Getter + private boolean tiled = false; + @Getter + private ColorType colorType = null; + @Getter + private boolean nonOpaque = false; + @Getter + private int colorOverride = 0; /** * @param loc location of the image to draw @@ -553,7 +571,8 @@ public UITexture build() { private DataResult buildForCodec() { // no error throwing and no drawable registration - return create().map(texture -> this.colorOverride != 0 ? texture.withColorOverride(this.colorOverride) : texture); + return create() + .map(texture -> this.colorOverride != 0 ? texture.withColorOverride(this.colorOverride) : texture); } private DataResult create() { @@ -567,9 +586,11 @@ private DataResult create() { this.v1 = 1; this.mode = Mode.RELATIVE; } else if (this.mode == Mode.PIXEL) { - if (this.iw <= 0 || this.ih <= 0) return DataResult.error(() -> "Image size must be > 0 for sub area via xywh or ltrb"); + if (this.iw <= 0 || this.ih <= 0) + return DataResult.error(() -> "Image size must be > 0 for sub area via xywh or ltrb"); if (this.x < 0 || this.y < 0 || this.w > this.iw || this.h > this.ih) { - return DataResult.error(() -> "X and Y must be > 0 and W and H must by smaller than the specified image size"); + return DataResult.error( + () -> "X and Y must be > 0 and W and H must by smaller than the specified image size"); } float tw = 1f / this.iw, th = 1f / this.ih; this.u0 = this.x * tw; @@ -586,7 +607,8 @@ private DataResult create() { if (this.iw <= 0 || this.ih <= 0) { return DataResult.error(() -> "Image size must be > 0 for adaptable textures (border > 0)"); } - return DataResult.success(new AdaptableUITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, + return DataResult.success(new AdaptableUITexture(this.location, this.u0, this.v0, this.u1, this.v1, + this.colorType, this.nonOpaque, 0, this.iw, this.ih, this.bl, this.bt, this.br, this.bb, this.tiled)); } if (this.tiled) { @@ -596,7 +618,8 @@ private DataResult create() { return DataResult.success(new TiledUITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque, 0, this.iw, this.ih)); } - return DataResult.success(new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, this.colorType, this.nonOpaque)); + return DataResult.success(new UITexture(this.location, this.u0, this.v0, this.u1, this.v1, + this.colorType, this.nonOpaque)); } return DataResult.error(() -> "Unknown error"); } diff --git a/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java b/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java index 398fdf0c..f33121f5 100644 --- a/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java +++ b/src/main/java/brachy/modularui/drawable/graph/GraphAxis.java @@ -8,8 +8,8 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; -import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.blaze3d.vertex.VertexConsumer; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; import org.joml.Matrix4f; diff --git a/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java b/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java index 9547dc8c..cf0a09ec 100644 --- a/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java +++ b/src/main/java/brachy/modularui/drawable/graph/GraphDrawable.java @@ -10,9 +10,9 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.RenderType; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexConsumer; - import lombok.Getter; import java.util.ArrayList; @@ -285,12 +285,16 @@ public GraphDrawable graphAspectRatio(float aspectRatio) { public final boolean equals(Object o) { if (!(o instanceof GraphDrawable that)) return false; - return backgroundColor == that.backgroundColor && Float.compare(majorTickThickness, that.majorTickThickness) == 0 && + return backgroundColor == that.backgroundColor && + Float.compare(majorTickThickness, that.majorTickThickness) == 0 && Float.compare(majorTickLength, that.majorTickLength) == 0 && Float.compare(minorTickThickness, that.minorTickThickness) == 0 && - Float.compare(minorTickLength, that.minorTickLength) == 0 && Float.compare(gridLineWidth, that.gridLineWidth) == 0 && - gridLineColor == that.gridLineColor && Float.compare(minorGridLineWidth, that.minorGridLineWidth) == 0 && - minorGridLineColor == that.minorGridLineColor && view.equals(that.view) && x.equals(that.x) && y.equals(that.y) && + Float.compare(minorTickLength, that.minorTickLength) == 0 && + Float.compare(gridLineWidth, that.gridLineWidth) == 0 && + gridLineColor == that.gridLineColor && + Float.compare(minorGridLineWidth, that.minorGridLineWidth) == 0 && + minorGridLineColor == that.minorGridLineColor && view.equals(that.view) && x.equals(that.x) && + y.equals(that.y) && plots.equals(that.plots); } diff --git a/src/main/java/brachy/modularui/drawable/graph/Plot.java b/src/main/java/brachy/modularui/drawable/graph/Plot.java index 1a183ff8..b17324e0 100644 --- a/src/main/java/brachy/modularui/drawable/graph/Plot.java +++ b/src/main/java/brachy/modularui/drawable/graph/Plot.java @@ -1,17 +1,17 @@ package brachy.modularui.drawable.graph; -import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.api.GuiAxis; import brachy.modularui.drawable.GuiDraw; import brachy.modularui.utils.Color; import brachy.modularui.utils.Interpolations; +import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.utils.math.DAM; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.util.Mth; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; public class Plot { diff --git a/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java index 2a8257cd..754733bc 100644 --- a/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/AbstractProgressDrawable.java @@ -10,7 +10,8 @@ public abstract class AbstractProgressDrawable> extends BaseProgressDrawable { - @Getter private IDrawable filledTexture; + @Getter + private IDrawable filledTexture; @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { @@ -23,7 +24,8 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget if (p < 1f) context.getStencil().pop(); } - protected abstract void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme); + protected abstract void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme); /** * Sets the filled texture which is partially drawn based on the current progress. diff --git a/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java index ba97dda4..736c99f9 100644 --- a/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/BaseProgressDrawable.java @@ -16,9 +16,12 @@ public abstract class BaseProgressDrawable> implements IDrawable { - @Getter private IDrawable emptyBackground; - @Getter private DoubleSupplier progress; - @Getter protected float progressStepSize = 0; + @Getter + private IDrawable emptyBackground; + @Getter + private DoubleSupplier progress; + @Getter + protected float progressStepSize = 0; @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { @@ -84,7 +87,8 @@ public D progressDuration(long duration, TimeUnit unit) { /** * Sets a progress step size. The displayed progress will be clamped to the closest multiple of this value. - * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always 0. + * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always + * 0. * * @param progressStepSize progress step size * @return this. @@ -109,7 +113,6 @@ public D emptyTexture(IDrawable drawable) { return self(); } - @SuppressWarnings("unchecked") protected D self() { return (D) this; diff --git a/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java index 010e7b78..4c8d8133 100644 --- a/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/CircularProgressDrawable.java @@ -6,25 +6,28 @@ import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.util.Mth; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; - import lombok.Getter; import org.joml.Matrix4f; /** - * A progress texture which translates the progress into a circular angle. This works with any {@link brachy.modularui.api.drawable.IDrawable}. + * A progress texture which translates the progress into a circular angle. This works with any + * {@link brachy.modularui.api.drawable.IDrawable}. */ public class CircularProgressDrawable extends AbstractProgressDrawable { - @Getter private Direction direction = Direction.CW; + @Getter + private Direction direction = Direction.CW; @Override - protected void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + protected void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme) { final float p = progress; float angle = p * Mth.TWO_PI; context.getStencil().push(() -> { @@ -138,6 +141,7 @@ public int hashCode() { } public enum Direction { - CW, CCW + CW, + CCW } } diff --git a/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java b/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java index 4901a2aa..eb515d36 100644 --- a/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java +++ b/src/main/java/brachy/modularui/drawable/progress/CompositeProgress.java @@ -1,13 +1,11 @@ package brachy.modularui.drawable.progress; -import net.minecraft.util.Mth; - import brachy.modularui.api.drawable.IDrawable; import brachy.modularui.screen.viewport.GuiContext; import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.Rectangle; -import brachy.modularui.utils.math.MathUtils; +import net.minecraft.util.Mth; import lombok.Getter; import org.jetbrains.annotations.NotNull; @@ -24,7 +22,8 @@ public class CompositeProgress extends BaseProgressDrawable { /** - * Creates a circle like, 4-slice progress bar. The texture is split into four quadrants which are drawn in either left, right, up + * Creates a circle like, 4-slice progress bar. The texture is split into four quadrants which are drawn in either + * left, right, up * or down direction. * * @param emptyTexture empty texture which is always displayed fully @@ -32,7 +31,8 @@ public class CompositeProgress extends BaseProgressDrawable { * @param direction clockwise or counterclockwise direction * @return progress drawable */ - public static CompositeProgress circularLike4Slice(IDrawable emptyTexture, IDrawable fullTexture, CircularProgressDrawable.Direction direction) { + public static CompositeProgress circularLike4Slice(IDrawable emptyTexture, IDrawable fullTexture, + CircularProgressDrawable.Direction direction) { CompositeProgress prog = new CompositeProgress().emptyTexture(emptyTexture); if (direction == CircularProgressDrawable.Direction.CCW) { prog.add(fullTexture, 0, 0, 0.5f, 0.5f, ProgressDrawable.Direction.DOWN, 0.25f) @@ -47,10 +47,10 @@ public static CompositeProgress circularLike4Slice(IDrawable emptyTexture, IDraw .add(fullTexture, 0, 0.5f, 0.5f, 1, ProgressDrawable.Direction.UP, 1f); } return prog; - } - @Getter private final List parts = new ArrayList<>(); + @Getter + private final List parts = new ArrayList<>(); private boolean dirty = true; @Override @@ -91,15 +91,17 @@ public CompositeProgress add(BaseProgressDrawable progress, float until, Unar return add(new Part(progress, until, area)); } - public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, ProgressDrawable.Direction direction, float untilProgress) { + public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, + ProgressDrawable.Direction direction, float untilProgress) { return add(filledTexture, u0, v0, u1, v1, direction, untilProgress, 0); } - public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, ProgressDrawable.Direction direction, float untilProgress, int progressPixelStep) { + public CompositeProgress add(IDrawable filledTexture, float u0, float v0, float u1, float v1, + ProgressDrawable.Direction direction, float untilProgress, int progressPixelStep) { return add(new ProgressDrawable() - .direction(direction) - .filledTexture(filledTexture.getSubArea(u0, v0, u1, v1)) - .progressPixelStepSize(progressPixelStep), + .direction(direction) + .filledTexture(filledTexture.getSubArea(u0, v0, u1, v1)) + .progressPixelStepSize(progressPixelStep), untilProgress, r -> { r.subArea(u0, v0, u1, v1); diff --git a/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java b/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java index 2ce74cbb..4428a4bc 100644 --- a/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java +++ b/src/main/java/brachy/modularui/drawable/progress/ProgressDrawable.java @@ -8,16 +8,20 @@ import lombok.Getter; /** - * A standard progress drawable which can display a progress bar with any {@link brachy.modularui.api.drawable.IDrawable} + * A standard progress drawable which can display a progress bar with any + * {@link brachy.modularui.api.drawable.IDrawable} * in the directions left, right, up and down. */ public class ProgressDrawable extends AbstractProgressDrawable { - @Getter private Direction direction = Direction.RIGHT; - @Getter private float progressPixelStepSize = 0; + @Getter + private Direction direction = Direction.RIGHT; + @Getter + private float progressPixelStepSize = 0; @Override - public void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + public void pushProgressStencil(float progress, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme) { float u0 = 0, u1 = 1, v0 = 0, v1 = 1; switch (this.direction) { case LEFT -> u0 = 1 - progress; @@ -32,7 +36,8 @@ public void pushProgressStencil(float progress, GuiContext context, int x, int y protected float getCurrentProgressStepSize(int width, int height) { float stepSize = this.progressStepSize; float pixelStepSize = this.progressPixelStepSize; - if (stepSize == 0 && pixelStepSize == 0 && !ModularUIConfig.smoothProgressBars() && getFilledTexture() instanceof UITexture) { + if (stepSize == 0 && pixelStepSize == 0 && !ModularUIConfig.smoothProgressBars() && + getFilledTexture() instanceof UITexture) { pixelStepSize = 1; } if (pixelStepSize > 0) { @@ -94,7 +99,8 @@ public ProgressDrawable down() { /** * Sets a progress step size. The displayed progress will be clamped to the closest multiple of this value. - * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always 0. + * Small values are smooth and high values are choppy. Values higher than 1 means the displayed progress is always + * 0. * * @param progressStepSize progress step size * @return this. diff --git a/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java b/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java index ee0d4f9c..6d648d10 100755 --- a/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/ArraySchema.java @@ -248,7 +248,7 @@ public ArraySchema build() { validate(); BlockState[][][] blocks = new BlockState[this.tensor .size()][this.tensor.getFirst().length][this.tensor.getFirst()[0] - .length()]; + .length()]; for (int x = 0; x < this.tensor.size(); x++) { String[] xLayer = this.tensor.get(x); for (int y = 0; y < xLayer.length; y++) { diff --git a/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java b/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java index bd1393e5..ebdd20a4 100755 --- a/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java +++ b/src/main/java/brachy/modularui/drawable/schema/BaseSchemaRenderer.java @@ -45,6 +45,10 @@ import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.client.model.data.ModelData; + +import com.google.common.collect.Lists; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.shaders.FogShape; @@ -58,10 +62,6 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexSorting; -import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; -import net.neoforged.neoforge.client.model.data.ModelData; - -import com.google.common.collect.Lists; import it.unimi.dsi.fastutil.objects.ObjectArraySet; import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; @@ -99,12 +99,16 @@ public class BaseSchemaRenderer implements IDrawable { private static final DummyLightTexture lightTexture = new DummyLightTexture(); - @Getter private final ISchema schema; + @Getter + private final ISchema schema; private final RenderLevel renderLevel; private final Viewport viewport = new Viewport(); - @Getter private final Camera camera = new Camera(); - @Getter private BlockHitResult lastRayTrace = null; - @Getter private RenderFilter renderFilter = RenderFilter.ALL; + @Getter + private final Camera camera = new Camera(); + @Getter + private BlockHitResult lastRayTrace = null; + @Getter + private RenderFilter renderFilter = RenderFilter.ALL; private RenderCompileTask lastRenderCompileTask = null; private final SectionBufferBuilderPack sectionBufferBuilders; @@ -113,9 +117,13 @@ public class BaseSchemaRenderer implements IDrawable { private boolean dirty = true; // projection * model view matrix - @Getter private final Matrix4f projection = new Matrix4f(); - @Getter @Setter private boolean captureDebugInfo; - @Getter private final Vector3f openGLMousePos = new Vector3f(); + @Getter + private final Matrix4f projection = new Matrix4f(); + @Getter + @Setter + private boolean captureDebugInfo; + @Getter + private final Vector3f openGLMousePos = new Vector3f(); private final List pos = new ArrayList<>(); public BaseSchemaRenderer(ISchema schema) { @@ -160,8 +168,9 @@ protected void recompile() { RenderCompileResults compileResults = new RenderCompileResults(); CompletableFuture.supplyAsync( - Util.wrapThreadWithTaskName("scm_chk_rebuild", () -> this.lastRenderCompileTask.compileBlockBuffers(compileResults)), - Util.backgroundExecutor()) + Util.wrapThreadWithTaskName("scm_chk_rebuild", + () -> this.lastRenderCompileTask.compileBlockBuffers(compileResults)), + Util.backgroundExecutor()) .thenCompose(Function.identity()) .whenComplete((result, error) -> { if (error != null) { @@ -269,8 +278,7 @@ public void drawBlockOutlines(MultiBufferSource.BufferSource bufferSource) { vc, p.getX(), p.getY(), p.getZ(), p.getX() + 1, p.getY() + 1, p.getZ() + 1, - 1f, 0f, 0f, 1f - ); + 1f, 0f, 0f, 1f); } } bufferSource.endBatch(RenderType.lines()); @@ -298,7 +306,6 @@ private RenderCompileResults checkRecompile() { // if we're still compiling, send previous result return res; - } @SuppressWarnings("deprecation") @@ -385,7 +392,8 @@ protected void renderBlocks(RenderCompileResults renderResult, RenderType render ShaderInstance shader = RenderSystem.getShader(); assert shader != null; - shader.setDefaultUniforms(renderType.mode(),RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), + shader.setDefaultUniforms(renderType.mode(), RenderSystem.getModelViewMatrix(), + RenderSystem.getProjectionMatrix(), Minecraft.getInstance().getWindow()); if (shader.CHUNK_OFFSET != null) { shader.CHUNK_OFFSET.set(-camera.pos().x, -camera.pos().y, -camera.pos().z); @@ -416,7 +424,8 @@ protected void renderBlocks(RenderCompileResults renderResult, RenderType render renderType.clearRenderState(); } - protected void renderBlockEntities(RenderCompileResults renderResult, MultiBufferSource bufferSource, float partialTick) { + protected void renderBlockEntities(RenderCompileResults renderResult, MultiBufferSource bufferSource, + float partialTick) { PoseStack poseStack = new PoseStack(); for (BlockEntity blockEntity : renderResult.blockEntities) { @@ -446,7 +455,8 @@ protected void handleBlockEntity(PoseStack poseStack, Mu protected void setupCamera(int width, int height) { // setup viewport and clear GL buffers int clearColor = getClearColor(); - RenderSystem.clearColor(Color.getRedF(clearColor), Color.getGreenF(clearColor), Color.getBlueF(clearColor), Color.getAlphaF(clearColor)); + RenderSystem.clearColor(Color.getRedF(clearColor), Color.getGreenF(clearColor), Color.getBlueF(clearColor), + Color.getAlphaF(clearColor)); RenderSystem.backupProjectionMatrix(); float near = 0.05f; @@ -513,7 +523,8 @@ protected BlockHitResult rayTrace(int mouseX, int mouseY, int width, int height) var p = e.getKey(); boolean reuseVec = this.pos.size() > i; var vec = reuseVec ? this.pos.get(i) : new Vector3f(); - vec = m.project(p.getX() + 0.5f, p.getY() + 0.5f, p.getZ() + 0.5f, this.viewport.getViewport(), vec); + vec = m.project(p.getX() + 0.5f, p.getY() + 0.5f, p.getZ() + 0.5f, this.viewport.getViewport(), + vec); if (reuseVec) this.pos.set(i, vec); else this.pos.add(vec); i++; @@ -561,7 +572,8 @@ public Vector3f screenToOpenGLPos(int x, int y, int width, int height, float dep return screenToOpenGLPos(x, y, width, height, depth, false, dest); } - private Vector3f screenToOpenGLPos(int x, int y, int width, int height, float depth, boolean readDepth, Vector3f dest) { + private Vector3f screenToOpenGLPos(int x, int y, int width, int height, float depth, boolean readDepth, + Vector3f dest) { this.viewport.rescaleToViewport(x, y, width, height, dest); if (readDepth) depth = MatrixUtils.readDepth((int) dest.x, (int) dest.y); dest.z = depth; @@ -569,7 +581,8 @@ private Vector3f screenToOpenGLPos(int x, int y, int width, int height, float de } public Vector3f screenToWorldPos(int x, int y, int screenWidth, int screenHeight) { - return screenToWorldPos(projection(), screenToOpenGLPos(x, y, screenWidth, screenHeight, new Vector3f()), new Vector3f()); + return screenToWorldPos(projection(), screenToOpenGLPos(x, y, screenWidth, screenHeight, new Vector3f()), + new Vector3f()); } private Vector3f screenToWorldPos(Matrix4f projection, Vector3f openGLPos) { @@ -627,7 +640,8 @@ public void updateRenderFilter(RenderFilter renderFilter) { public boolean equals(Object o) { if (!(o instanceof BaseSchemaRenderer that)) return false; - return this.schema.equals(that.schema) && this.renderLevel.equals(that.renderLevel) && this.camera.equals(that.camera) && + return this.schema.equals(that.schema) && this.renderLevel.equals(that.renderLevel) && + this.camera.equals(that.camera) && Objects.equals(this.viewport, that.viewport) && Objects.equals(this.renderFilter, that.renderFilter); } @@ -666,7 +680,8 @@ protected CompletableFuture compileBlockBuffers(RenderComp RandomSource randomSource = RandomSource.create(); PoseStack poseStack = new PoseStack(); - Map bufferLayers = new Reference2ObjectArrayMap<>(RenderType.chunkBufferLayers().size()); + Map bufferLayers = new Reference2ObjectArrayMap<>( + RenderType.chunkBufferLayers().size()); ModelBlockRenderer.enableCaching(); int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE; @@ -771,7 +786,8 @@ protected CompletableFuture compileBlockBuffers(RenderComp } protected BufferBuilder getOrBeginLayer(Map bufferLayers, - SectionBufferBuilderPack sectionBufferBuilderPack, RenderType renderType) { + SectionBufferBuilderPack sectionBufferBuilderPack, + RenderType renderType) { BufferBuilder builder = bufferLayers.get(renderType); if (builder == null) { ByteBufferBuilder bytebufferbuilder = sectionBufferBuilderPack.buffer(renderType); @@ -782,7 +798,8 @@ protected BufferBuilder getOrBeginLayer(Map bufferLay return builder; } - protected CompletableFuture uploadChunkLayer(RenderCompileResults results, MeshData meshData, RenderType renderType) { + protected CompletableFuture uploadChunkLayer(RenderCompileResults results, MeshData meshData, + RenderType renderType) { return CompletableFuture.runAsync(() -> { VertexBuffer buffer = results.getOrCreateChunkBuffers().get(renderType); if (!buffer.isInvalid()) { diff --git a/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java b/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java index b171999f..cd0e5aed 100755 --- a/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java +++ b/src/main/java/brachy/modularui/drawable/schema/BlockHighlight.java @@ -7,6 +7,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; @@ -14,7 +15,6 @@ import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; - import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -32,12 +32,12 @@ public class BlockHighlight { static { int[][] intVertices = { - {1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0}, - {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0}, - {0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0}, - {0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1}, - {0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0}, - {1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0} + { 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0 }, + { 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0 }, + { 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1 }, + { 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0 }, + { 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0 } }; for (int i = 0; i < 6; i++) { for (int j = 0; j < 12; j++) { diff --git a/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java b/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java index 328b877c..5fedd335 100755 --- a/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/BoxSchema.java @@ -43,7 +43,8 @@ public BlockPos getOrigin() { public boolean equals(Object o) { if (!(o instanceof BoxSchema entries)) return false; - return level.equals(entries.level) && min.equals(entries.min) && max.equals(entries.max) && center.equals(entries.center); + return level.equals(entries.level) && min.equals(entries.min) && max.equals(entries.max) && + center.equals(entries.center); } @Override diff --git a/src/main/java/brachy/modularui/drawable/schema/DummyChunkSource.java b/src/main/java/brachy/modularui/drawable/schema/DummyChunkSource.java index d5b627b2..692170bf 100644 --- a/src/main/java/brachy/modularui/drawable/schema/DummyChunkSource.java +++ b/src/main/java/brachy/modularui/drawable/schema/DummyChunkSource.java @@ -40,7 +40,8 @@ public boolean clear() { // remove all 'filled' blocks from the schema level this.chunks.values().forEach(chunk -> { ChunkPos chunkPos = chunk.getPos(); - for (BlockPos pos : BlockPos.betweenClosed(chunkPos.getMinBlockX(), chunk.getMinBuildHeight(), chunkPos.getMinBlockZ(), + for (BlockPos pos : BlockPos.betweenClosed(chunkPos.getMinBlockX(), chunk.getMinBuildHeight(), + chunkPos.getMinBlockZ(), chunkPos.getMaxBlockX(), chunk.getMaxBuildHeight(), chunkPos.getMaxBlockZ())) { this.level.removeFilledBlock(pos); } diff --git a/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java b/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java index e83dd799..b94aeb08 100755 --- a/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java +++ b/src/main/java/brachy/modularui/drawable/schema/DummyLightTexture.java @@ -6,9 +6,9 @@ import net.minecraft.util.Mth; import net.minecraft.world.level.LevelTimeAccess; import net.minecraft.world.level.lighting.LightEngine; + import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; - import org.joml.Vector3f; import org.joml.Vector3fc; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java b/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java index 0b2a7ea5..0c28e922 100755 --- a/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java +++ b/src/main/java/brachy/modularui/drawable/schema/LiquidVertexConsumer.java @@ -3,9 +3,9 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.SectionPos; + import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; - import org.joml.Matrix4f; import javax.annotation.ParametersAreNonnullByDefault; @@ -98,7 +98,8 @@ public void putBulkData(PoseStack.Pose poseEntry, BakedQuad quad, float red, flo public void putBulkData(PoseStack.Pose poseEntry, BakedQuad quad, float[] brightness, float red, float green, float blue, float alpha, int[] combinedLights, int combinedOverlay, boolean mulColor) { - delegate.putBulkData(poseEntry, quad, brightness, red, green, blue, alpha, combinedLights, combinedOverlay, mulColor); + delegate.putBulkData(poseEntry, quad, brightness, red, green, blue, alpha, combinedLights, combinedOverlay, + mulColor); } @Override diff --git a/src/main/java/brachy/modularui/drawable/schema/MapSchema.java b/src/main/java/brachy/modularui/drawable/schema/MapSchema.java index 28579fa7..c3671544 100755 --- a/src/main/java/brachy/modularui/drawable/schema/MapSchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/MapSchema.java @@ -83,7 +83,8 @@ public Vector3fc getFocus() { public Iterator> iterator() { return new AbstractIterator<>() { - private final ObjectIterator> it = blocks.long2ReferenceEntrySet().fastIterator(); + private final ObjectIterator> it = blocks.long2ReferenceEntrySet() + .fastIterator(); @Override protected Map.Entry computeNext() { diff --git a/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java b/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java index 1bb80609..94db9d6c 100755 --- a/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java +++ b/src/main/java/brachy/modularui/drawable/schema/PosListSchema.java @@ -2,19 +2,15 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import lombok.Getter; -import lombok.Setter; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import java.util.Iterator; import java.util.Map; -import java.util.Objects; -import java.util.function.BiPredicate; public abstract class PosListSchema implements ISchema { diff --git a/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java b/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java index 3f31dafc..74ce4580 100644 --- a/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java +++ b/src/main/java/brachy/modularui/drawable/schema/RenderLevel.java @@ -30,13 +30,15 @@ import org.jetbrains.annotations.Nullable; import java.util.List; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class RenderLevel implements LevelTimeAccess { - @Getter private final ISchema schema; + @Getter + private final ISchema schema; private final Level level; private final RenderFilter renderFilter; private final Thread thread; diff --git a/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java b/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java index ea66cf68..c1069a61 100755 --- a/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java +++ b/src/main/java/brachy/modularui/drawable/schema/SchemaLevel.java @@ -34,10 +34,8 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.DataLayer; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.level.entity.LevelCallback; import net.minecraft.world.level.entity.LevelEntityGetter; @@ -66,6 +64,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Stream; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault diff --git a/src/main/java/brachy/modularui/drawable/schema/Viewport.java b/src/main/java/brachy/modularui/drawable/schema/Viewport.java index 4d03251a..1433081d 100644 --- a/src/main/java/brachy/modularui/drawable/schema/Viewport.java +++ b/src/main/java/brachy/modularui/drawable/schema/Viewport.java @@ -2,9 +2,9 @@ import net.minecraft.client.Minecraft; import net.minecraft.util.Mth; + import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.systems.RenderSystem; - import lombok.Getter; import org.joml.Vector3f; @@ -12,7 +12,8 @@ public class Viewport { - @Getter private final int[] viewport = new int[4]; + @Getter + private final int[] viewport = new int[4]; public void setX(int x) { this.viewport[0] = x; @@ -81,7 +82,8 @@ public float unscaleYFromViewport(float viewportY, float nonViewportHeight) { return (1f - ((viewportY - getY()) / (float) getH())) * nonViewportHeight; } - public Vector3f unscaleFromViewport(float viewportX, float viewportY, float nonViewportWidth, float nonViewportHeight, Vector3f dest) { + public Vector3f unscaleFromViewport(float viewportX, float viewportY, float nonViewportWidth, + float nonViewportHeight, Vector3f dest) { dest.x = unscaleXFromViewport(viewportX, nonViewportWidth); dest.y = unscaleYFromViewport(viewportY, nonViewportHeight); return dest; diff --git a/src/main/java/brachy/modularui/drawable/text/AnimatedText.java b/src/main/java/brachy/modularui/drawable/text/AnimatedText.java index d909a391..9531b6d7 100644 --- a/src/main/java/brachy/modularui/drawable/text/AnimatedText.java +++ b/src/main/java/brachy/modularui/drawable/text/AnimatedText.java @@ -2,127 +2,130 @@ // TODO turn into ComponentsContents /* -@Accessors(fluent = true, chain = true) -public class AnimatedText extends StyledText { - - private MutableComponent full; - private String fullString; - private String currentString = ""; - private int currentIndex; - /** - * How fast the characters appear - *//* - @Setter - private int speed = 40; // ms per char - private long timeLastDraw; - @Setter - private boolean forward = true; - - private boolean isAnimating = false; - - public AnimatedText(IKey key) { - super(key); - } - - @Override - public MutableComponent get() { - return Component.literal(this.currentString); - } - - public void reset() { - this.full = null; - } - - private void advance() { - if (!this.isAnimating || (this.forward && this.currentIndex >= this.fullString.length()) || - (!this.forward && this.currentIndex < 0)) - return; - long time = Util.getMillis(); - int amount = (int) ((time - this.timeLastDraw) / this.speed); - if (amount == 0) return; - if (this.forward) { - int max = Math.min(this.fullString.length() - 1, this.currentIndex + amount); - this.currentIndex = Math.max(this.currentIndex, 0); - for (int i = this.currentIndex; i < max; i++) { - char c = this.fullString.charAt(i); - if (c == ' ') { - max = Math.min(this.fullString.length() - 1, max + 1); - } - // noinspection StringConcatenationInLoop - this.currentString += c; - } - this.currentIndex = max; - } else { - int min = Math.max(0, this.currentIndex - amount); - this.currentIndex = Math.min(this.currentIndex, this.currentString.length() - 1); - for (int i = this.currentIndex; i >= min; i--) { - char c = this.fullString.charAt(i); - if (c == ' ') { - min = Math.max(0, min - 1); - } - this.currentString = this.currentString.substring(0, i); - } - this.currentIndex = min; - } - this.timeLastDraw += (long) amount * this.speed; - } - - @OnlyIn(Dist.CLIENT) - @Override - public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { - if (this.full == null || !this.full.equals(super.get())) { - if (this.isAnimating) { - this.full = super.get(); - this.fullString = this.full.getString(); - this.currentString = this.forward ? "" : this.fullString; - this.currentIndex = this.forward ? 0 : this.fullString.length() - 1; - this.timeLastDraw = Util.getMillis(); - } else { - this.currentString = this.forward ? "" : this.fullString; - } - } - advance(); - if (this.currentString.isEmpty()) return; - super.draw(context, x, y, width, height, widgetTheme); - } - - public AnimatedText startAnimation() { - this.isAnimating = true; - return this; - } - - public AnimatedText stopAnimation() { - this.isAnimating = false; - return this; - } - - @Override - public @NotNull AnimatedText style(ChatFormatting formatting) { - return (AnimatedText) super.style(formatting); - } - - @Override - public @NotNull AnimatedText alignment(Alignment alignment) { - return (AnimatedText) super.alignment(alignment); - } - - @Override - public @NotNull AnimatedText color(int color) { - return color(() -> color); - } - - @Override - public @NotNull AnimatedText color(@Nullable IntSupplier color) { - return (AnimatedText) super.color(color); - } - - @Override - public @NotNull AnimatedText scale(float scale) { - return (AnimatedText) super.scale(scale); - } - - @Override - public @NotNull AnimatedText shadow(@Nullable Boolean shadow) { - return (AnimatedText) super.shadow(shadow); - } -}*/ + * @Accessors(fluent = true, chain = true) + * public class AnimatedText extends StyledText { + * + * private MutableComponent full; + * private String fullString; + * private String currentString = ""; + * private int currentIndex; + * /** + * How fast the characters appear + *//* + * @Setter + * private int speed = 40; // ms per char + * private long timeLastDraw; + * + * @Setter + * private boolean forward = true; + * + * private boolean isAnimating = false; + * + * public AnimatedText(IKey key) { + * super(key); + * } + * + * @Override + * public MutableComponent get() { + * return Component.literal(this.currentString); + * } + * + * public void reset() { + * this.full = null; + * } + * + * private void advance() { + * if (!this.isAnimating || (this.forward && this.currentIndex >= this.fullString.length()) || + * (!this.forward && this.currentIndex < 0)) + * return; + * long time = Util.getMillis(); + * int amount = (int) ((time - this.timeLastDraw) / this.speed); + * if (amount == 0) return; + * if (this.forward) { + * int max = Math.min(this.fullString.length() - 1, this.currentIndex + amount); + * this.currentIndex = Math.max(this.currentIndex, 0); + * for (int i = this.currentIndex; i < max; i++) { + * char c = this.fullString.charAt(i); + * if (c == ' ') { + * max = Math.min(this.fullString.length() - 1, max + 1); + * } + * // noinspection StringConcatenationInLoop + * this.currentString += c; + * } + * this.currentIndex = max; + * } else { + * int min = Math.max(0, this.currentIndex - amount); + * this.currentIndex = Math.min(this.currentIndex, this.currentString.length() - 1); + * for (int i = this.currentIndex; i >= min; i--) { + * char c = this.fullString.charAt(i); + * if (c == ' ') { + * min = Math.max(0, min - 1); + * } + * this.currentString = this.currentString.substring(0, i); + * } + * this.currentIndex = min; + * } + * this.timeLastDraw += (long) amount * this.speed; + * } + * + * @OnlyIn(Dist.CLIENT) + * + * @Override + * public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + * if (this.full == null || !this.full.equals(super.get())) { + * if (this.isAnimating) { + * this.full = super.get(); + * this.fullString = this.full.getString(); + * this.currentString = this.forward ? "" : this.fullString; + * this.currentIndex = this.forward ? 0 : this.fullString.length() - 1; + * this.timeLastDraw = Util.getMillis(); + * } else { + * this.currentString = this.forward ? "" : this.fullString; + * } + * } + * advance(); + * if (this.currentString.isEmpty()) return; + * super.draw(context, x, y, width, height, widgetTheme); + * } + * + * public AnimatedText startAnimation() { + * this.isAnimating = true; + * return this; + * } + * + * public AnimatedText stopAnimation() { + * this.isAnimating = false; + * return this; + * } + * + * @Override + * public @NotNull AnimatedText style(ChatFormatting formatting) { + * return (AnimatedText) super.style(formatting); + * } + * + * @Override + * public @NotNull AnimatedText alignment(Alignment alignment) { + * return (AnimatedText) super.alignment(alignment); + * } + * + * @Override + * public @NotNull AnimatedText color(int color) { + * return color(() -> color); + * } + * + * @Override + * public @NotNull AnimatedText color(@Nullable IntSupplier color) { + * return (AnimatedText) super.color(color); + * } + * + * @Override + * public @NotNull AnimatedText scale(float scale) { + * return (AnimatedText) super.scale(scale); + * } + * + * @Override + * public @NotNull AnimatedText shadow(@Nullable Boolean shadow) { + * return (AnimatedText) super.shadow(shadow); + * } + * } + */ diff --git a/src/main/java/brachy/modularui/drawable/text/ComposedLine.java b/src/main/java/brachy/modularui/drawable/text/ComposedLine.java index 16619549..ba57ff23 100755 --- a/src/main/java/brachy/modularui/drawable/text/ComposedLine.java +++ b/src/main/java/brachy/modularui/drawable/text/ComposedLine.java @@ -53,7 +53,9 @@ public void draw(GuiContext context, Font font, float x, float y, int color, boo } x += w; } else if (o != null) { - throw new IllegalArgumentException("ComposedLine objects must either be a FormattedCharSequence or an IIcon, but found a " + o.getClass().getSimpleName() + "!"); + throw new IllegalArgumentException( + "ComposedLine objects must either be a FormattedCharSequence or an IIcon, but found a " + + o.getClass().getSimpleName() + "!"); } } } diff --git a/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java b/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java index e83af5fc..317cd47a 100644 --- a/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java +++ b/src/main/java/brachy/modularui/drawable/text/DynamicComponent.java @@ -26,7 +26,8 @@ public class DynamicComponent implements Component, IDrawable { private long time = -1; private final Supplier supplier; private Style style = Style.EMPTY; - @Getter private float scale = 1f; + @Getter + private float scale = 1f; private Component lastComp; public DynamicComponent(Supplier supplier) { diff --git a/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java b/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java index 44ab8b37..c97cb40c 100755 --- a/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java +++ b/src/main/java/brachy/modularui/drawable/text/FontRenderHelper.java @@ -17,9 +17,7 @@ import net.minecraft.network.chat.Style; import net.minecraft.util.FormattedCharSequence; import net.minecraft.util.FormattedCharSink; - import net.neoforged.api.distmarker.Dist; - import net.neoforged.api.distmarker.OnlyIn; import org.apache.commons.lang3.mutable.MutableBoolean; @@ -67,12 +65,14 @@ public static int getDefaultTextHeight() { } @OnlyIn(Dist.CLIENT) - public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme) { drawComponent(comp, context, x, y, width, height, widgetTheme, 1f); } @OnlyIn(Dist.CLIENT) - public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme, float scale) { + public static void drawComponent(Component comp, GuiContext context, int x, int y, int width, int height, + WidgetTheme widgetTheme, float scale) { Text.renderer.setAlignment(Alignment.CENTER, width, height); Text.renderer.setColor(widgetTheme.getTextColor()); Text.renderer.setScale(scale); @@ -251,11 +251,13 @@ public interface StyleSink { } private static boolean feedChar(Style style, FormattedCharSink sink, int position, char character) { - return Character.isSurrogate(character) ? sink.accept(position, style, 65533) : sink.accept(position, style, character); + return Character.isSurrogate(character) ? sink.accept(position, style, 65533) : + sink.accept(position, style, character); } /** - * Copied and edited from {@link net.minecraft.util.StringDecomposer#iterateFormatted(String, int, Style, Style, FormattedCharSink)}. + * Copied and edited from + * {@link net.minecraft.util.StringDecomposer#iterateFormatted(String, int, Style, Style, FormattedCharSink)}. */ public static boolean iterateFormatted(String text, int skip, Style currentStyle, Style defaultStyle, FormattedCharSink sink, StyleSink styleSink) { @@ -274,7 +276,8 @@ public static boolean iterateFormatted(String text, int skip, Style currentStyle char c1 = text.charAt(j + 1); ChatFormatting chatformatting = ChatFormatting.getByCode(c1); if (chatformatting != null) { - style = chatformatting == ChatFormatting.RESET ? defaultStyle : style.applyLegacyFormat(chatformatting); + style = chatformatting == ChatFormatting.RESET ? defaultStyle : + style.applyLegacyFormat(chatformatting); styleChanged = true; } diff --git a/src/main/java/brachy/modularui/drawable/text/ModularComponent.java b/src/main/java/brachy/modularui/drawable/text/ModularComponent.java index 2ea7dfb4..f206109b 100644 --- a/src/main/java/brachy/modularui/drawable/text/ModularComponent.java +++ b/src/main/java/brachy/modularui/drawable/text/ModularComponent.java @@ -7,8 +7,6 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import brachy.modularui.widgets.TextWidget; -import com.demonwav.mcdev.annotations.Translatable; - import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.ComponentContents; @@ -23,8 +21,9 @@ import net.minecraft.network.chat.contents.ScoreContents; import net.minecraft.network.chat.contents.SelectorContents; import net.minecraft.network.chat.contents.TranslatableContents; -import com.mojang.serialization.Codec; +import com.demonwav.mcdev.annotations.Translatable; +import com.mojang.serialization.Codec; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -38,9 +37,11 @@ public class ModularComponent extends MutableComponent implements Text { - public static final MutableObjectCodec CODEC = MutableObjectCodec.drawableBuilder(ModularComponent.class, "Text") + public static final MutableObjectCodec CODEC = MutableObjectCodec + .drawableBuilder(ModularComponent.class, "Text") .wrapped(ComponentSerialization.CODEC.xmap(ModularComponent::of, mc -> mc)) - .addOpt("alignment", ModularComponent::alignment, ModularComponent::getAlignment, Alignment.CODEC, Alignment.Center) + .addOpt("alignment", ModularComponent::alignment, ModularComponent::getAlignment, Alignment.CODEC, + Alignment.Center) .addOpt("scale", ModularComponent::scale, ModularComponent::getScale, Codec.FLOAT, 1f) .addOpt("shadow", ModularComponent::shadow, ModularComponent::getShadow, Codec.BOOL, null) .addUnencodable("dynamicColor", ModularComponent::color, ModularComponent::getDynamicColor) @@ -62,7 +63,8 @@ public static ModularComponent translatableWithFallback(@Translatable String key return ModularComponent.create(new TranslatableContents(key, fallback, TranslatableContents.NO_ARGS)); } - public static ModularComponent translatableWithFallback(@Translatable String key, @Nullable String fallback, Object... args) { + public static ModularComponent translatableWithFallback(@Translatable String key, @Nullable String fallback, + Object... args) { return ModularComponent.create(new TranslatableContents(key, fallback, args)); } @@ -74,7 +76,8 @@ public static ModularComponent keybind(String name) { return ModularComponent.create(new KeybindContents(name)); } - public static ModularComponent nbt(String nbtPathPattern, boolean interpreting, Optional separator, DataSource dataSource) { + public static ModularComponent nbt(String nbtPathPattern, boolean interpreting, Optional separator, + DataSource dataSource) { return ModularComponent.create(new NbtContents(nbtPathPattern, interpreting, separator, dataSource)); } @@ -92,13 +95,18 @@ public static ModularComponent create(@NotNull ComponentContents contents) { public static ModularComponent of(Component component) { if (component instanceof ModularComponent mc) return mc; - return new ModularComponent(component.getContents(), new ArrayList<>(component.getSiblings()), component.getStyle()); + return new ModularComponent(component.getContents(), new ArrayList<>(component.getSiblings()), + component.getStyle()); } - @Getter private Alignment alignment = Alignment.CENTER; - @Getter private float scale = 1f; - @Getter private Boolean shadow; - @Getter private IntSupplier dynamicColor; + @Getter + private Alignment alignment = Alignment.CENTER; + @Getter + private float scale = 1f; + @Getter + private Boolean shadow; + @Getter + private IntSupplier dynamicColor; protected ModularComponent(ComponentContents contents, List siblings, Style style) { super(contents, siblings, style); @@ -213,7 +221,7 @@ public ModularComponent asModular() { } @Override - public @NotNull ModularComponent withStyle(ChatFormatting @NotNull ... formats) { + public @NotNull ModularComponent withStyle(ChatFormatting @NotNull... formats) { return (ModularComponent) super.withStyle(formats); } @@ -236,7 +244,8 @@ public ModularComponent asModular() { public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof ModularComponent other)) return false; - return super.equals(other) && this.alignment.equals(other.alignment) && Float.compare(this.scale, other.scale) == 0 && + return super.equals(other) && this.alignment.equals(other.alignment) && + Float.compare(this.scale, other.scale) == 0 && Objects.equals(this.shadow, other.shadow) && Objects.equals(this.dynamicColor, other.dynamicColor); } diff --git a/src/main/java/brachy/modularui/drawable/text/RichText.java b/src/main/java/brachy/modularui/drawable/text/RichText.java index 28824fee..02bb24cd 100644 --- a/src/main/java/brachy/modularui/drawable/text/RichText.java +++ b/src/main/java/brachy/modularui/drawable/text/RichText.java @@ -19,13 +19,12 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.ComponentSerialization; import net.minecraft.network.chat.FormattedText; -import net.minecraft.util.ExtraCodecs; + import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.Decoder; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.Encoder; - import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import lombok.Getter; @@ -45,6 +44,7 @@ public class RichText implements IDrawable, IRichTextBuilder { ModularComponent.CODEC.codec(), ComponentSerialization.CODEC, Spacer.CODEC_MAP.codec(), Codec.STRING, IDrawable.CODEC); private static final Encoder RICH_ELEMENT_ENCODER = new Encoder<>() { + @Override public DataResult encode(Object input, DynamicOps ops, T prefix) { if (input == null) return DataResult.success(ops.empty()); @@ -57,7 +57,8 @@ public DataResult encode(Object input, DynamicOps ops, T prefix) { if (input instanceof Component v) return ComponentSerialization.CODEC.encode(v, ops, prefix); if (input instanceof IDrawable v) return IDrawable.CODEC.encode(v, ops, prefix); if (input instanceof Spacer v) return Spacer.CODEC_MAP.codec().encode(v, ops, prefix); - return DataResult.error(() -> "RichText is currently unable to encode objects of type " + input.getClass().getSimpleName()); + return DataResult.error( + () -> "RichText is currently unable to encode objects of type " + input.getClass().getSimpleName()); } }; public static final Codec RICH_ELEMENT_CODEC = Codec.of(RICH_ELEMENT_ENCODER, RICH_ELEMENT_DECODER); @@ -72,10 +73,14 @@ public DataResult encode(Object input, DynamicOps ops, T prefix) { private final List elements = new ArrayList<>(); private TooltipLines componentList; - @Getter private Alignment alignment = Alignment.CenterLeft; - @Getter private float scale = 1f; - @Getter private Integer color = null; - @Getter private Boolean shadow = null; + @Getter + private Alignment alignment = Alignment.CenterLeft; + @Getter + private float scale = 1f; + @Getter + private Integer color = null; + @Getter + private Boolean shadow = null; private int cursor = 0; private boolean cursorLocked = false; @@ -371,7 +376,8 @@ public void draw(GuiContext context, int x, int y, int width, int height, int co draw(renderer, context, x, y, width, height, color, shadow); } - public void draw(TextRenderer renderer, GuiContext context, int x, int y, int width, int height, int color, boolean shadow) { + public void draw(TextRenderer renderer, GuiContext context, int x, int y, int width, int height, int color, + boolean shadow) { if (ModularUI.isDev() && !this.verified) { verifyListElements(this.elements); this.verified = true; @@ -389,7 +395,8 @@ public int getLastHeight() { return (int) renderer.getLastHeight(); } - public void setupRenderer(TextRenderer renderer, int x, int y, float width, float height, int color, boolean shadow) { + public void setupRenderer(TextRenderer renderer, int x, int y, float width, float height, int color, + boolean shadow) { renderer.setPos(x, y); renderer.setScale(this.scale); renderer.setColor(this.color != null ? this.color : color); @@ -479,7 +486,8 @@ public static void verifyListElements(List elements) { continue; } if (!errored.contains(o.getClass())) { - errors.add("Element of type '" + o.getClass() + "' is not valid for RichText. Elements must implement one of these interfaces: [FormattedText, IIcon, ITextLine]"); + errors.add("Element of type '" + o.getClass() + + "' is not valid for RichText. Elements must implement one of these interfaces: [FormattedText, IIcon, ITextLine]"); errored.add(o.getClass()); } } diff --git a/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java b/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java index acf29e29..665727f8 100755 --- a/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java +++ b/src/main/java/brachy/modularui/drawable/text/RichTextCompiler.java @@ -108,7 +108,8 @@ private void compile(List raw) { } private boolean iterateFormatted(String content, int skip, Style style) { - return FontRenderHelper.iterateFormatted(content, skip, style, Style.EMPTY, this.lineBreakFinder, this.lineBreakFinder); + return FontRenderHelper.iterateFormatted(content, skip, style, Style.EMPTY, this.lineBreakFinder, + this.lineBreakFinder); } private void compileText(Component component) { @@ -195,7 +196,7 @@ private void addLineElement(String s, Style style, float width) { if (s.isEmpty()) return; this.h = Math.max(this.h, this.fr.lineHeight); this.x += width; - //if (s.length() > 1) s = this.fr.bidirectionalShaping(s); // TODO: this turns ", " into " ," for some reason + // if (s.length() > 1) s = this.fr.bidirectionalShaping(s); // TODO: this turns ", " into " ," for some reason this.currentLine.add(FormattedCharSequence.forward(s, style)); } diff --git a/src/main/java/brachy/modularui/drawable/text/Spacer.java b/src/main/java/brachy/modularui/drawable/text/Spacer.java index 3eb45d38..26b9dea1 100755 --- a/src/main/java/brachy/modularui/drawable/text/Spacer.java +++ b/src/main/java/brachy/modularui/drawable/text/Spacer.java @@ -4,9 +4,9 @@ import brachy.modularui.screen.viewport.GuiContext; import net.minecraft.client.gui.Font; + import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; - import lombok.Getter; public class Spacer implements ITextLine { diff --git a/src/main/java/brachy/modularui/drawable/text/TextRenderer.java b/src/main/java/brachy/modularui/drawable/text/TextRenderer.java index 00cfd69f..02f411f9 100644 --- a/src/main/java/brachy/modularui/drawable/text/TextRenderer.java +++ b/src/main/java/brachy/modularui/drawable/text/TextRenderer.java @@ -260,7 +260,8 @@ protected int getStartX(float maxWidth, float lineWidth) { maxWidth = this.maxWidth; } if (this.alignment.x > 0 && maxWidth > 0) { - return Math.max(this.x, this.x + Math.round(maxWidth * this.alignment.x) - Math.round(lineWidth * this.alignment.x)); + return Math.max(this.x, + this.x + Math.round(maxWidth * this.alignment.x) - Math.round(lineWidth * this.alignment.x)); } return this.x; } diff --git a/src/main/java/brachy/modularui/factory/GuiData.java b/src/main/java/brachy/modularui/factory/GuiData.java index 17f99d09..dae5737f 100644 --- a/src/main/java/brachy/modularui/factory/GuiData.java +++ b/src/main/java/brachy/modularui/factory/GuiData.java @@ -16,7 +16,8 @@ * This class and subclasses are holding necessary data to find the exact same GUI on client and server. * For example, if the GUI was opened by right-clicking a BlockEntity, then this data needs a world and a block pos. *

- * Also see {@link PosGuiData} (useful for BlockEntities) and {@link SidedPosGuiData} (useful for covers from GregTech) and + * Also see {@link PosGuiData} (useful for BlockEntities) and {@link SidedPosGuiData} (useful for covers from GregTech) + * and * {@link PlayerInventoryGuiData} (useful for GUIs opened by interacting with an item in the players inventory) * for default implementations. *

diff --git a/src/main/java/brachy/modularui/factory/GuiManager.java b/src/main/java/brachy/modularui/factory/GuiManager.java index f2bf791d..4061b823 100644 --- a/src/main/java/brachy/modularui/factory/GuiManager.java +++ b/src/main/java/brachy/modularui/factory/GuiManager.java @@ -72,7 +72,8 @@ public static boolean hasFactory(ResourceLocation name) { return FACTORIES.containsKey(name); } - public static void open(@NotNull UIFactory factory, @NotNull T guiData, ServerPlayer player) { + public static void open(@NotNull UIFactory factory, @NotNull T guiData, + ServerPlayer player) { if (player instanceof FakePlayer || openedContainers.contains(player)) return; openedContainers.add(player); // create panel, collect sync handlers and create menu @@ -90,7 +91,8 @@ public static void open(@NotNull UIFactory factory, @NotN player.closeContainer(); } int windowId = ((ServerPlayerAccessor) player).getContainerCounter(); - ModularContainerMenu menu = settings.hasCustomContainer() ? settings.createContainer(windowId) : factory.createContainer(windowId); + ModularContainerMenu menu = settings.hasCustomContainer() ? settings.createContainer(windowId) : + factory.createContainer(windowId); menu.construct(player, msm, settings, panel.getName(), guiData); // sync to client @@ -110,7 +112,8 @@ public static void open(@NotNull UIFactory factory, @NotN @ApiStatus.Internal @OnlyIn(Dist.CLIENT) public static void openFromClient(int windowId, int networkId, @NotNull UIFactory factory, - @NotNull RegistryFriendlyByteBuf data, @NotNull Player player) { + @NotNull RegistryFriendlyByteBuf data, + @NotNull Player player) { T guiData = factory.readGuiData(player, data); UISettings settings = new UISettings(); settings.defaultCanInteractWith(factory, guiData); @@ -121,9 +124,11 @@ public static void openFromClient(int windowId, int networkI guiData.addSyncHandlers(syncManager); ModularScreen screen = factory.createScreen(guiData, panel); screen.getContext().setSettings(settings); - ModularContainerMenu container = settings.hasCustomContainer() ? settings.createContainer(windowId) : factory.createContainer(windowId); + ModularContainerMenu container = settings.hasCustomContainer() ? settings.createContainer(windowId) : + factory.createContainer(windowId); container.construct(player, msm, settings, panel.getName(), guiData); - IMuiScreen wrapper = settings.hasCustomGui() ? settings.createGui(container, screen) : factory.createScreenWrapper(container, screen); + IMuiScreen wrapper = settings.hasCustomGui() ? settings.createGui(container, screen) : + factory.createScreenWrapper(container, screen); if (!(wrapper.wrappedScreen() instanceof AbstractContainerScreen guiContainer)) { throw new IllegalStateException("The wrapping screen must be a GuiContainer for synced GUIs!"); } @@ -139,14 +144,16 @@ public static void openFromClient(int windowId, int networkI public static void openFromClient(@NotNull UIFactory factory, @NotNull T guiData) { // notify server to open the gui // server will send packet back to actually open the gui - RegistryFriendlyByteBuf buffer = IRegistryFriendlyByteBufExtension.createEmpty(MCHelper.getMc().getConnection().registryAccess()); + RegistryFriendlyByteBuf buffer = IRegistryFriendlyByteBufExtension + .createEmpty(MCHelper.getMc().getConnection().registryAccess()); factory.writeGuiData(guiData, buffer); PacketDistributor.sendToServer(new OpenGuiPacket<>(0, 0, factory, buffer)); } @OnlyIn(Dist.CLIENT) static void openScreen(ModularScreen screen, UISettings settings) { - if (screen.getScreenWrapper() != null && MCHelper.getCurrentScreen() == screen.getScreenWrapper().wrappedScreen()) { + if (screen.getScreenWrapper() != null && + MCHelper.getCurrentScreen() == screen.getScreenWrapper().wrappedScreen()) { // already open return; } diff --git a/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java b/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java index 11fb2d5a..b31ae042 100644 --- a/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java +++ b/src/main/java/brachy/modularui/factory/PlayerInventoryGuiData.java @@ -21,7 +21,8 @@ @Getter public class PlayerInventoryGuiData extends GuiData { - public static PlayerInventoryGuiData of(Player player, InventoryType inventoryType, T context, int slotIndex) { + public static PlayerInventoryGuiData of(Player player, InventoryType inventoryType, T context, + int slotIndex) { return new PlayerInventoryGuiData<>(player, inventoryType, context, slotIndex); } diff --git a/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java b/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java index 107effde..996c3a43 100755 --- a/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java +++ b/src/main/java/brachy/modularui/factory/PlayerInventoryUIFactory.java @@ -35,7 +35,8 @@ public void openFromCurios(Player player, String type, int index) { if (!ModularUI.Mods.CURIOS.isLoaded()) { throw new IllegalArgumentException("Can't open UI for curio item when curios is not loaded!"); } - GuiManager.open(this, PlayerInventoryGuiData.of(player, InventoryTypes.CURIOS, type, index), verifyServerSide(player)); + GuiManager.open(this, PlayerInventoryGuiData.of(player, InventoryTypes.CURIOS, type, index), + verifyServerSide(player)); } public void open(Player player, InventoryType type, T context, int index) { diff --git a/src/main/java/brachy/modularui/factory/UIFactories.java b/src/main/java/brachy/modularui/factory/UIFactories.java index 49551d37..2490a025 100755 --- a/src/main/java/brachy/modularui/factory/UIFactories.java +++ b/src/main/java/brachy/modularui/factory/UIFactories.java @@ -1,9 +1,9 @@ package brachy.modularui.factory; -import net.minecraft.resources.ResourceLocation; - import brachy.modularui.api.IUIHolder; +import net.minecraft.resources.ResourceLocation; + import org.jetbrains.annotations.ApiStatus; import java.util.function.Supplier; diff --git a/src/main/java/brachy/modularui/factory/inventory/InventoryType.java b/src/main/java/brachy/modularui/factory/inventory/InventoryType.java index fd7a3ae6..3d7ee986 100755 --- a/src/main/java/brachy/modularui/factory/inventory/InventoryType.java +++ b/src/main/java/brachy/modularui/factory/inventory/InventoryType.java @@ -66,7 +66,7 @@ public boolean isActive() { * @return index of slot with stackable item or -1 if none found */ public int findFirstStackable(Player player, ItemStack stack, boolean ignoreEmpty) { - int[] holder = {-1}; + int[] holder = { -1 }; visitAllStackable(player, stack, (type, context, index, stackInSlot) -> { if (stackInSlot.isEmpty() && ignoreEmpty) return false; holder[0] = index; diff --git a/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java b/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java index 7e62d330..16ba0d5b 100755 --- a/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java +++ b/src/main/java/brachy/modularui/factory/inventory/InventoryTypes.java @@ -6,11 +6,11 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.InputConstants; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.neoforge.client.event.InputEvent; import net.neoforged.neoforge.common.NeoForge; +import com.mojang.blaze3d.platform.InputConstants; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; @@ -73,7 +73,7 @@ public static Collection> getAll() { * @param stack item stack to check stackability for * @param visitor visitor function */ - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public static void visitAllStackable(Player player, ItemStack stack, InventoryVisitor visitor) { for (InventoryType type : getAll()) { if (type.visitAllStackable(player, stack, visitor)) { @@ -90,7 +90,7 @@ public static void visitAllStackable(Player player, ItemStack stack, InventoryVi * @param player the player to visit inventory in * @param visitor visitor function */ - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public static void visitAll(Player player, InventoryVisitor visitor) { for (InventoryType type : getAll()) { if (type.visitAll(player, visitor)) { diff --git a/src/main/java/brachy/modularui/integration/embeddium/SodiumCompat.java b/src/main/java/brachy/modularui/integration/embeddium/SodiumCompat.java index 0af2cd13..d1a952be 100644 --- a/src/main/java/brachy/modularui/integration/embeddium/SodiumCompat.java +++ b/src/main/java/brachy/modularui/integration/embeddium/SodiumCompat.java @@ -1,8 +1,7 @@ package brachy.modularui.integration.embeddium; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; - import net.caffeinemc.mods.sodium.api.texture.SpriteUtil; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; import java.util.Collection; diff --git a/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java b/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java index 5b9fc5d8..718db3ef 100644 --- a/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java +++ b/src/main/java/brachy/modularui/integration/emi/EmiRecipeViewerSlot.java @@ -4,13 +4,12 @@ import brachy.modularui.integration.recipeviewer.RecipeSlotRole; import brachy.modularui.integration.recipeviewer.RecipeViewerSlotWidget; import brachy.modularui.screen.viewport.ModularGuiContext; +import brachy.modularui.theme.WidgetThemeEntry; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.world.item.crafting.Ingredient; import net.neoforged.neoforge.fluids.FluidStack; -import brachy.modularui.theme.WidgetThemeEntry; - import dev.emi.emi.api.stack.EmiIngredient; import dev.emi.emi.api.widget.SlotWidget; import dev.emi.emi.api.widget.TankWidget; @@ -20,7 +19,8 @@ @ApiStatus.Internal public class EmiRecipeViewerSlot extends RecipeViewerSlotWidget> { - @Getter private SlotWidget slotWidget; + @Getter + private SlotWidget slotWidget; public EmiRecipeViewerSlot(Class ingredientClass) { super(ingredientClass); @@ -30,7 +30,8 @@ public EmiRecipeViewerSlot(Class ingredientClass) { tooltipAutoUpdate(true); tooltipDynamic(tooltip -> { - for (ClientTooltipComponent ctc : this.slotWidget.getTooltip(getContext().getAbsMouseX(), getContext().getAbsMouseY())) { + for (ClientTooltipComponent ctc : this.slotWidget.getTooltip(getContext().getAbsMouseX(), + getContext().getAbsMouseY())) { tooltip.addDrawableLine(new TooltipComponentIcon(ctc, false)); } }); @@ -38,7 +39,8 @@ public EmiRecipeViewerSlot(Class ingredientClass) { @Override protected void rebuildRealSlot() { - EmiIngredient ingredient = EmiStackConverter.convertToEmiEntry(this.entries, this.chance, this.renderMappingFunction); + EmiIngredient ingredient = EmiStackConverter.convertToEmiEntry(this.entries, this.chance, + this.renderMappingFunction); if (this.ingredientClass == FluidStack.class) { // special case fluid slots slotWidget = new TankWidget(ingredient, 0, 0, 18, 18, 1); @@ -51,12 +53,14 @@ protected void rebuildRealSlot() { @Override public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { - this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), context.getRenderPartialTicks()); + this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), + context.getRenderPartialTicks()); } @Override public Result onMousePressed(int button) { - return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS : Result.ACCEPT; + return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? + Result.SUCCESS : Result.ACCEPT; } @Override diff --git a/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java b/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java index 0cd1d434..49ef26e2 100644 --- a/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java +++ b/src/main/java/brachy/modularui/integration/emi/EmiStackConverter.java @@ -6,24 +6,20 @@ import brachy.modularui.integration.recipeviewer.handlers.IngredientProvider; import brachy.modularui.utils.math.MathUtils; -import dev.emi.emi.api.neoforge.NeoForgeEmiStack; - import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; - -import dev.emi.emi.api.stack.EmiIngredient; -import dev.emi.emi.api.stack.EmiStack; -import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; - import net.neoforged.neoforge.capabilities.Capabilities; import net.neoforged.neoforge.fluids.FluidStack; import net.neoforged.neoforge.fluids.capability.IFluidHandler; - import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; +import dev.emi.emi.api.neoforge.NeoForgeEmiStack; +import dev.emi.emi.api.stack.EmiIngredient; +import dev.emi.emi.api.stack.EmiStack; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import org.jetbrains.annotations.Nullable; import java.util.Map; @@ -65,17 +61,17 @@ public EmiIngredient convertTo(EntryList stack, float chance, UnaryOp return toEMIIngredient(stackList.stream().map(mapper)).setChance(chance); } else if (stack instanceof ItemTagList tagList) { return EmiIngredient.of(tagList.getEntries().stream() - .map(ItemTagList.ItemTagEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - tagList.getEntries().getFirst().amount()) + .map(ItemTagList.ItemTagEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + tagList.getEntries().getFirst().amount()) .setChance(chance); } else if (stack instanceof ItemHolderSetList holderSetList) { return EmiIngredient.of(holderSetList.getEntries().stream() - .map(ItemHolderSetList.ItemHolderSetEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - holderSetList.getEntries().getFirst().amount()) + .map(ItemHolderSetList.ItemHolderSetEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + holderSetList.getEntries().getFirst().amount()) .setChance(chance); } return EmiStack.EMPTY; @@ -87,12 +83,13 @@ public EmiIngredient convertTo(EntryList stack, float chance, UnaryOp public @Nullable FluidStack convertFrom(EmiStack stack) { Fluid key = stack.getKeyOfType(Fluid.class); if (key != null && key != Fluids.EMPTY) { - return new FluidStack(key.builtInRegistryHolder(), MathUtils.saturatedCast(stack.getAmount()), stack.getComponentChanges()); + return new FluidStack(key.builtInRegistryHolder(), MathUtils.saturatedCast(stack.getAmount()), + stack.getComponentChanges()); } var item = ITEM.convertFrom(stack); if (item != null) { IFluidHandlerItem fluidHandler = item.getCapability(Capabilities.FluidHandler.ITEM); - if(fluidHandler != null && fluidHandler.getTanks() == 1) { + if (fluidHandler != null && fluidHandler.getTanks() == 1) { return fluidHandler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE); } } @@ -112,17 +109,17 @@ public EmiIngredient convertTo(EntryList stack, float chance, UnaryO return toEMIIngredient(stackList.stream().map(mapper)).setChance(chance); } else if (stack instanceof FluidTagList tagList) { return EmiIngredient.of(tagList.getEntries().stream() - .map(FluidTagList.FluidTagEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - tagList.getEntries().getFirst().amount()) + .map(FluidTagList.FluidTagEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + tagList.getEntries().getFirst().amount()) .setChance(chance); } else if (stack instanceof FluidHolderSetList holderSetList) { return EmiIngredient.of(holderSetList.getEntries().stream() - .map(FluidHolderSetList.FluidHolderSetEntry::stacks) - .map(stream -> toEMIIngredient(stream.map(mapper))) - .collect(Collectors.toList()), - holderSetList.getEntries().getFirst().amount()) + .map(FluidHolderSetList.FluidHolderSetEntry::stacks) + .map(stream -> toEMIIngredient(stream.map(mapper))) + .collect(Collectors.toList()), + holderSetList.getEntries().getFirst().amount()) .setChance(chance); } return EmiStack.EMPTY; @@ -144,7 +141,8 @@ public static Optional> getFor(Class clazz) { return Optional.ofNullable(getForNullable(clazz)); } - public static EmiIngredient convertToEmiEntry(EntryList entries, float chance, UnaryOperator renderMappingFunction) { + public static EmiIngredient convertToEmiEntry(EntryList entries, float chance, + UnaryOperator renderMappingFunction) { Converter converter = getForNullable(entries.getType()); if (converter != null) { return converter.convertTo(entries, chance, renderMappingFunction); diff --git a/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java b/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java index 5df34a5c..2694258e 100644 --- a/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java +++ b/src/main/java/brachy/modularui/integration/emi/ModularUIEmiPlugin.java @@ -4,7 +4,6 @@ import brachy.modularui.integration.emi.handler.EmiScreenHandler; import brachy.modularui.screen.ContainerScreenWrapper; import brachy.modularui.screen.ScreenWrapper; - import brachy.modularui.test.TestRecipeViewerGuis; import dev.emi.emi.api.EmiEntrypoint; diff --git a/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java b/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java index c2461406..2bb66324 100755 --- a/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java +++ b/src/main/java/brachy/modularui/integration/emi/handler/EmiScreenHandler.java @@ -29,7 +29,7 @@ import java.util.function.Consumer; public class EmiScreenHandler extends RecipeViewerHandler - implements EmiExclusionArea, EmiDragDropHandler, EmiStackProvider { + implements EmiExclusionArea, EmiDragDropHandler, EmiStackProvider { private static final Map, EmiScreenHandler> CACHE = new Reference2ReferenceOpenHashMap<>(); @@ -102,7 +102,7 @@ public EmiStackInteraction getStackAt(T screen, int x, int y) { if (converter == null) { return EmiStackInteraction.EMPTY; } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) var converted = ((EmiStackConverter.Converter) converter).convertTo(provider); return new EmiStackInteraction(converted, null, false); } diff --git a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java index f04e9c18..4886f811 100644 --- a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java +++ b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiCategory.java @@ -1,10 +1,10 @@ package brachy.modularui.integration.emi.recipe; +import brachy.modularui.integration.recipeviewer.RecipeViewerUtils; + import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; -import brachy.modularui.integration.recipeviewer.RecipeViewerUtils; - import dev.emi.emi.api.recipe.EmiRecipe; import dev.emi.emi.api.recipe.EmiRecipeCategory; import dev.emi.emi.api.render.EmiRenderable; @@ -21,7 +21,8 @@ public ModularUIEmiCategory(ResourceLocation id, EmiRenderable icon, EmiRenderab super(id, icon, simplified); } - public ModularUIEmiCategory(ResourceLocation id, EmiRenderable icon, EmiRenderable simplified, Comparator sorter) { + public ModularUIEmiCategory(ResourceLocation id, EmiRenderable icon, EmiRenderable simplified, + Comparator sorter) { super(id, icon, simplified, sorter); } diff --git a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java index 7cc13f0e..6d1f9a8d 100644 --- a/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java +++ b/src/main/java/brachy/modularui/integration/emi/recipe/ModularUIEmiRecipe.java @@ -37,12 +37,14 @@ public abstract class ModularUIEmiRecipe implements EmiRecipe { private static final String SCREEN_NAME_PREFIX = "emi_recipe_"; - private static final LoadingCache PREVIEW_SCREEN_CACHE = CacheBuilder.newBuilder() + private static final LoadingCache PREVIEW_SCREEN_CACHE = CacheBuilder + .newBuilder() .expireAfterAccess(Duration.ofSeconds(60)) .initialCapacity(8) .maximumSize(32) .softValues() .build(new CacheLoader<>() { + @Override public ModularScreen load(ModularUIEmiRecipe key) { return key.createScreen(); @@ -59,7 +61,8 @@ private static ModularScreen getCachedModularScreen(ModularUIEmiRecipe recipe) { return PREVIEW_SCREEN_CACHE.getUnchecked(recipe); } - @Getter private final ResourceLocation id; + @Getter + private final ResourceLocation id; private final Supplier recipeUI; private boolean sizeCalculated = false; @@ -82,7 +85,8 @@ public ModularUIEmiRecipe(ResourceLocation recipeId, int width, int height, Supp /** * Calculates the size of the recipe if not already done.
- * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category are calculated + * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category + * are calculated * at once, which can make the game lag for a few seconds. */ protected void calculateSize() { @@ -160,7 +164,8 @@ public IWidget transformWidget(IWidget widget) { private boolean useScreenCacheForNextWidgetQuery = false; /** - * This is used to make EMI's recipe tooltip components use the screen cache because those normally recreate the widgets every frame + * This is used to make EMI's recipe tooltip components use the screen cache because those normally recreate the + * widgets every frame */ @ApiStatus.Internal public final void useScreenCacheForNextWidgetQuery() { diff --git a/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java b/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java index b297153c..e6d42af3 100644 --- a/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java +++ b/src/main/java/brachy/modularui/integration/jei/JeiRecipeViewerSlot.java @@ -3,7 +3,6 @@ import brachy.modularui.drawable.TooltipComponentIcon; import brachy.modularui.integration.recipeviewer.RecipeViewerSlotWidget; import brachy.modularui.integration.recipeviewer.entry.EntryList; - import brachy.modularui.screen.viewport.ModularGuiContext; import brachy.modularui.theme.WidgetThemeEntry; import brachy.modularui.utils.TooltipLines; @@ -27,9 +26,11 @@ * Ingredient changes after building will only change the displayed ingredients. */ @ApiStatus.Internal -public class JeiRecipeViewerSlot extends RecipeViewerSlotWidget> implements ISlottedRecipeWidget { +public class JeiRecipeViewerSlot extends RecipeViewerSlotWidget> + implements ISlottedRecipeWidget { - @Getter private @Nullable IRecipeSlotDrawable slotWidget; + @Getter + private @Nullable IRecipeSlotDrawable slotWidget; private boolean configured; private boolean overrideDisplay; @@ -97,17 +98,18 @@ public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { this.slotWidget.draw(context.getGraphics(), isHovering()); } -/* - @Override - public Result onMousePressed(int button) { - return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS : Result.ACCEPT; - } - - @Override - public Result onKeyPressed(int keyCode, int scanCode, int modifiers) { - return this.slotWidget.keyPressed(keyCode, scanCode, modifiers) ? Result.SUCCESS : Result.ACCEPT; - } -*/ + /* + * @Override + * public Result onMousePressed(int button) { + * return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS + * : Result.ACCEPT; + * } + * + * @Override + * public Result onKeyPressed(int keyCode, int scanCode, int modifiers) { + * return this.slotWidget.keyPressed(keyCode, scanCode, modifiers) ? Result.SUCCESS : Result.ACCEPT; + * } + */ @Override public Optional getSlotUnderMouse(double mouseX, double mouseY) { diff --git a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java index 69b78917..a7dd2ff1 100644 --- a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java +++ b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiPlugin.java @@ -5,12 +5,11 @@ import brachy.modularui.integration.recipeviewer.RecipeSlotRole; import brachy.modularui.screen.ContainerScreenWrapper; import brachy.modularui.screen.ScreenWrapper; +import brachy.modularui.test.TestRecipeViewerGuis; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.resources.ResourceLocation; -import brachy.modularui.test.TestRecipeViewerGuis; - import lombok.Getter; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; @@ -30,8 +29,10 @@ @JeiPlugin public class ModularUIJeiPlugin implements IModPlugin { - @Getter private static IJeiRuntime runtime = null; - @Getter private static IJeiHelpers jeiHelpers; + @Getter + private static IJeiRuntime runtime = null; + @Getter + private static IJeiHelpers jeiHelpers; public static boolean hasRuntime() { return runtime != null; @@ -87,7 +88,7 @@ public void registerGuiHandlers(IGuiHandlerRegistration registration) { public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) { if (ModularUI.Mods.REI.isLoaded() || ModularUI.Mods.EMI.isLoaded()) return; - //JeiContainerHandler.register(ModularContainerMenu.class, registration); + // JeiContainerHandler.register(ModularContainerMenu.class, registration); } @Override diff --git a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java index 1adb9501..65b1858a 100644 --- a/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java +++ b/src/main/java/brachy/modularui/integration/jei/ModularUIJeiProperties.java @@ -7,7 +7,6 @@ import net.minecraft.client.gui.screens.Screen; import com.mojang.blaze3d.platform.Window; - import lombok.Getter; import lombok.experimental.Accessors; import mezz.jei.api.gui.handlers.IGuiProperties; @@ -42,7 +41,7 @@ public ModularUIJeiProperties(IMuiScreen screen) { this.screenClass = screen.wrappedScreen().getClass(); // we have to assign default values to gui size if the size is 0 (e.g. during the instant it's created) - // because MUI initializes the screen/panel sizing data after JEI wants to use them + // because MUI initializes the screen/panel sizing data after JEI wants to use them Window window = Minecraft.getInstance().getWindow(); Area screenArea = screen.screen().getScreenArea(); this.screenWidth = screenArea.width == 0 ? window.getGuiScaledWidth() : screenArea.width; diff --git a/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java b/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java index 17a15cd4..401063be 100755 --- a/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java +++ b/src/main/java/brachy/modularui/integration/jei/handler/JeiContainerHandler.java @@ -23,7 +23,8 @@ public class JeiContainerHandler implements IUniversalRecipeTransferHandler { - public static void register(Class clz, IRecipeTransferRegistration registration) { + public static void register(Class clz, + IRecipeTransferRegistration registration) { new JeiContainerHandler<>(clz, registration.getTransferHelper()).register(registration); } diff --git a/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java b/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java index e9dc1002..5eed9462 100755 --- a/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java +++ b/src/main/java/brachy/modularui/integration/jei/handler/JeiScreenHandler.java @@ -36,7 +36,7 @@ import java.util.Optional; public class JeiScreenHandler extends RecipeViewerHandler - implements IGhostIngredientHandler, IScreenHandler { + implements IGhostIngredientHandler, IScreenHandler { private static final Map, JeiScreenHandler> CACHE = new Reference2ReferenceOpenHashMap<>(); @@ -97,7 +97,8 @@ public boolean shouldHighlightTargets() { } @Override - public Optional> getClickableIngredientUnderMouse(IClickableIngredientFactory factory, T screen, + public Optional> getClickableIngredientUnderMouse(IClickableIngredientFactory factory, + T screen, double mouseX, double mouseY) { IWidget hovered = screen.screen().getContext().getTopHovered(); if (hovered instanceof IngredientProvider provider) { @@ -116,7 +117,8 @@ private I mapFirstIngredient(IngredientProvider provider) { return provider.renderMappingFunction().apply(provider.getIngredients().getStacks().get(0)); } - private Optional> createClickableIngredient(IClickableIngredientFactory factory, I ingredient, + private Optional> createClickableIngredient(IClickableIngredientFactory factory, + I ingredient, Rectangle area) { Optional> type = ModularUIJeiPlugin.getJeiHelpers().getIngredientManager() .getIngredientTypeChecked(ingredient); @@ -162,10 +164,13 @@ public boolean isSearchFocused() { return new JeiRecipeViewerSlot<>(ingredientClass); } - public static class ContainerScreen & IMuiScreen> extends JeiScreenHandler implements IGuiContainerHandler { + public static class ContainerScreen & IMuiScreen> extends JeiScreenHandler + implements IGuiContainerHandler { @SuppressWarnings("unchecked") - public static & IMuiScreen> ContainerScreen ofContainer(Class clazz) { + public static & IMuiScreen> ContainerScreen ofContainer(Class clazz) { return (ContainerScreen) CACHE.computeIfAbsent(clazz, clz -> new ContainerScreen<>((Class) clz)); } diff --git a/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java b/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java index ae46482f..28d7a5dc 100644 --- a/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java +++ b/src/main/java/brachy/modularui/integration/jei/recipe/ModularUIJeiCategory.java @@ -62,6 +62,7 @@ protected ModularUIJeiCategory(Function recipeUI, Function() { + @Override public Dimensions load(T recipe) { return ModularUIJeiCategory.this.calculateSize(recipe); @@ -87,8 +88,10 @@ protected Dimensions calculateSize(T recipe) { /** * Calculates and caches the size of the recipe if not already done.
- * This should be called in subclasses' {@link #setupRecipeIngredients(IRecipeLayoutBuilder, Object, IFocusGroup) setupRecipeIngredients} methods. - * Otherwise, the size of ALL the recipes in the same category are calculated at once, which can make the game lag for a few seconds. + * This should be called in subclasses' {@link #setupRecipeIngredients(IRecipeLayoutBuilder, Object, IFocusGroup) + * setupRecipeIngredients} methods. + * Otherwise, the size of ALL the recipes in the same category are calculated at once, which can make the game lag + * for a few seconds. */ protected final void calculateAndCacheSize(T recipe) { this.displaySizeCache.getUnchecked(recipe); @@ -96,7 +99,8 @@ protected final void calculateAndCacheSize(T recipe) { /** * Return the maximum expected display width here.
- * You should also return a per-category display width that's at most this value in {@link #getWidth(Object)} if the default value + * You should also return a per-category display width that's at most this value in {@link #getWidth(Object)} if the + * default value * doesn't suit your needs. * * @return The maximum expected display width @@ -105,7 +109,8 @@ protected final void calculateAndCacheSize(T recipe) { /** * Return the maximum expected display height here.
- * You should also return a per-category display height that's at most this value in {@link #getHeight(Object)} if the default value + * You should also return a per-category display height that's at most this value in {@link #getHeight(Object)} if + * the default value * doesn't suit your needs. * * @return The maximum expected display height @@ -117,7 +122,8 @@ protected final void calculateAndCacheSize(T recipe) { * This is used by JEI for lookups, to figure out what ingredients are inputs and outputs for a recipe. * *

- * Note that you can only add inputs and outputs for JEI's recipe lookup/search here, as the layout builder that's + * Note that you can only add inputs and outputs for JEI's recipe lookup/search here, as the layout builder + * that's * passed into this method only handles those and not the displayed recipe previews. */ @ApiStatus.OverrideOnly @@ -162,14 +168,16 @@ public IWidget transformWidget(IRecipeExtrasBuilder builder, IWidget widget) { @ApiStatus.OverrideOnly @MustBeInvokedByOverriders - public IWidget createRecipeSlotForWidget(IRecipeLayoutBuilder builder, IWidget widget, T recipe, IFocusGroup focuses, MutableInt index) { + public IWidget createRecipeSlotForWidget(IRecipeLayoutBuilder builder, IWidget widget, T recipe, + IFocusGroup focuses, MutableInt index) { if (!(widget instanceof JeiRecipeViewerSlot recipeViewerSlot)) return widget; if (recipeViewerSlot.getName() == null) { recipeViewerSlot.name("jei_slot_" + index.getAndIncrement()); } - IRecipeSlotBuilder slotBuilder = builder.addSlot(ModularUIJeiPlugin.mapToJeiRole(recipeViewerSlot.recipeSlotRole())) + IRecipeSlotBuilder slotBuilder = builder + .addSlot(ModularUIJeiPlugin.mapToJeiRole(recipeViewerSlot.recipeSlotRole())) .setSlotName(recipeViewerSlot.getName()); recipeViewerSlot.configureJeiSlotBuilder(slotBuilder); @@ -191,12 +199,14 @@ public Component getTitle() { @Override public void setRecipe(IRecipeLayoutBuilder builder, T recipe, IFocusGroup focuses) { // guard against JEMI issues by explicitly checking for JEI's implementation - // this is also done to skip having to create the whole widget tree when JEI is only looking up the recipe's ingredients + // this is also done to skip having to create the whole widget tree when JEI is only looking up the recipe's + // ingredients // Check the mod first so compatibility runtimes without JEI do not load its builder class. if (ModularUI.Mods.JEI.isLoaded() && builder instanceof RecipeLayoutBuilder) { ModularScreen screen = createScreen(recipe); MutableInt index = new MutableInt(0); - screen.getMainPanel().visitTransformAllChildren(widget -> createRecipeSlotForWidget(builder, widget, recipe, focuses, index)); + screen.getMainPanel().visitTransformAllChildren( + widget -> createRecipeSlotForWidget(builder, widget, recipe, focuses, index)); veryTemporaryScreenCache.put(recipe, screen); } else { // don't bother with creating the full widget tree if setRecipe was called to get the recipe's ingredients @@ -221,7 +231,8 @@ public void createRecipeExtras(IRecipeExtrasBuilder builder, T recipe, IFocusGro } @Override - public void getTooltip(ITooltipBuilder tooltipBuilder, T recipe, IRecipeSlotsView recipeSlotsView, double mouseX, double mouseY) {} + public void getTooltip(ITooltipBuilder tooltipBuilder, T recipe, IRecipeSlotsView recipeSlotsView, double mouseX, + double mouseY) {} @Override public @Nullable IDrawable getIcon() { @@ -248,7 +259,7 @@ public int getWidth(T recipe) { return display.width; } - protected record Dimensions(int width, int height) { } + protected record Dimensions(int width, int height) {} public static class UIWrapperWidget implements IJeiGuiEventListener, IRecipeWidget { @@ -298,7 +309,7 @@ public void getTooltip(ITooltipBuilder tooltipBuilder, double mouseX, double mou @Override public void mouseMoved(double mouseX, double mouseY) { - //this.screen.mouseMoved(mouseX, mouseY); + // this.screen.mouseMoved(mouseX, mouseY); } @Override @@ -326,5 +337,4 @@ public boolean keyPressed(double mouseX, double mouseY, int keyCode, int scanCod return this.screen.keyPressed(keyCode, scanCode, modifiers); } } - } diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java index 2112239e..73ed119d 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerSlotWidget.java @@ -7,8 +7,6 @@ import brachy.modularui.integration.recipeviewer.entry.item.ItemStackList; import brachy.modularui.integration.recipeviewer.handlers.IngredientProvider; import brachy.modularui.integration.recipeviewer.handlers.RecipeViewerHandler; -import brachy.modularui.screen.viewport.ModularGuiContext; -import brachy.modularui.theme.WidgetThemeEntry; import brachy.modularui.widget.Widget; import net.minecraft.world.item.ItemStack; @@ -23,17 +21,23 @@ @Accessors(fluent = true) @ApiStatus.Experimental -public abstract class RecipeViewerSlotWidget> extends Widget implements Interactable { +public abstract class RecipeViewerSlotWidget> extends Widget + implements Interactable { - @Getter protected RecipeSlotRole recipeSlotRole = RecipeSlotRole.RENDER_ONLY; + @Getter + protected RecipeSlotRole recipeSlotRole = RecipeSlotRole.RENDER_ONLY; protected EntryList entries; - @Getter @Setter protected float chance = 1f; - @Getter @Setter protected UnaryOperator renderMappingFunction = UnaryOperator.identity(); + @Getter + @Setter + protected float chance = 1f; + @Getter + @Setter + protected UnaryOperator renderMappingFunction = UnaryOperator.identity(); protected final Class ingredientClass; public RecipeViewerSlotWidget(Class ingredientClass) { - this.ingredientClass = ingredientClass; + this.ingredientClass = ingredientClass; } public W recipeSlotRole(RecipeSlotRole recipeSlotRole) { @@ -60,7 +64,8 @@ public W value(I stack) { } else if (stack.getClass() == FluidStack.class) { return value((EntryList) FluidStackList.of((FluidStack) stack)); } else { - throw new IllegalArgumentException("Cannot use value(stack) with non-standard stack types! Use value(entryList) instead."); + throw new IllegalArgumentException( + "Cannot use value(stack) with non-standard stack types! Use value(entryList) instead."); } } diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java index c4ec300e..5cdad0b9 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerState.java @@ -7,18 +7,21 @@ public enum RecipeViewerState implements Predicate { ENABLED { + @Override public boolean test(ModularScreen screen) { return true; } }, DISABLED { + @Override public boolean test(ModularScreen screen) { return false; } }, DEFAULT { + @Override public boolean test(ModularScreen screen) { return !screen.isClientOnly(); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java index 21ffe030..fd6c28fc 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/RecipeViewerUtils.java @@ -12,5 +12,4 @@ private RecipeViewerUtils() {} public static Component getCategoryTitle(ResourceLocation categoryId) { return Component.translatable(categoryId.toLanguageKey(CATEGORY_LANGUAGE_KEY_PREFIX)); } - } diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java b/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java index f2ce88e2..e671262d 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidEntryList.java @@ -6,7 +6,8 @@ import java.util.List; -public sealed interface FluidEntryList extends EntryList permits FluidStackList, FluidTagList, FluidHolderSetList { +public sealed interface FluidEntryList extends EntryList + permits FluidStackList, FluidTagList, FluidHolderSetList { List getStacks(); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidHolderSetList.java b/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidHolderSetList.java index ea1c1d08..160bc850 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidHolderSetList.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/entry/fluid/FluidHolderSetList.java @@ -17,7 +17,8 @@ public final class FluidHolderSetList implements FluidEntryList { @Getter private final List entries = new ArrayList<>(); - public static FluidHolderSetList of(@NotNull HolderSet set, int amount, @NotNull DataComponentPatch componentPatch) { + public static FluidHolderSetList of(@NotNull HolderSet set, int amount, + @NotNull DataComponentPatch componentPatch) { var list = new FluidHolderSetList(); list.add(set, amount, componentPatch); return list; @@ -43,7 +44,8 @@ public List getStacks() { .toList(); } - public record FluidHolderSetEntry(@NotNull HolderSet set, int amount, @NotNull DataComponentPatch componentPatch) { + public record FluidHolderSetEntry(@NotNull HolderSet set, int amount, + @NotNull DataComponentPatch componentPatch) { public Stream stacks() { return set.stream().map(holder -> new FluidStack(holder, amount, componentPatch)); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java index 381e27aa..f400115f 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemEntryList.java @@ -6,7 +6,8 @@ import java.util.List; -public sealed interface ItemEntryList extends EntryList permits ItemStackList, ItemTagList, ItemHolderSetList { +public sealed interface ItemEntryList extends EntryList + permits ItemStackList, ItemTagList, ItemHolderSetList { List getStacks(); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemHolderSetList.java b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemHolderSetList.java index 3f847dac..3d0d7488 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemHolderSetList.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemHolderSetList.java @@ -17,7 +17,8 @@ public final class ItemHolderSetList implements ItemEntryList { @Getter private final List entries = new ArrayList<>(); - public static ItemHolderSetList of(@NotNull HolderSet set, int amount, @NotNull DataComponentPatch componentPatch) { + public static ItemHolderSetList of(@NotNull HolderSet set, int amount, + @NotNull DataComponentPatch componentPatch) { var list = new ItemHolderSetList(); list.add(set, amount, componentPatch); return list; @@ -43,7 +44,8 @@ public List getStacks() { .toList(); } - public record ItemHolderSetEntry(@NotNull HolderSet set, int amount, @NotNull DataComponentPatch componentPatch) { + public record ItemHolderSetEntry(@NotNull HolderSet set, int amount, + @NotNull DataComponentPatch componentPatch) { public Stream stacks() { return set.stream().map(holder -> ItemTagList.stackWithComponents(holder, amount, componentPatch)); diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemStackList.java b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemStackList.java index 2795ed9c..dca619da 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemStackList.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/entry/item/ItemStackList.java @@ -2,8 +2,6 @@ import net.minecraft.world.item.ItemStack; -import lombok.Getter; - import java.util.ArrayList; import java.util.Collection; import java.util.List; diff --git a/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java b/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java index 41db6bc1..84d9bed8 100644 --- a/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java +++ b/src/main/java/brachy/modularui/integration/recipeviewer/handlers/RecipeTransferError.java @@ -14,7 +14,7 @@ *

*/ public abstract sealed class RecipeTransferError permits RecipeTransferError.Internal, RecipeTransferError.UserFacing, - RecipeTransferError.Cosmetic { + RecipeTransferError.Cosmetic { public abstract boolean allowsTransfer(); @@ -40,7 +40,7 @@ public List getTooltip() { * has many (or all) of the items required for a recipe in their inventory, it is shown first. * * @return the number of input recipes slots are missing ingredient's in the player's inventory. - * Return -1 by default to avoid sorting + * Return -1 by default to avoid sorting * @since 19.2.0 */ public int getMissingCountHint() { diff --git a/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java b/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java index c8242c08..6cbfb657 100644 --- a/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java +++ b/src/main/java/brachy/modularui/integration/rei/ModularUIReiPlugin.java @@ -4,7 +4,6 @@ import brachy.modularui.integration.rei.handler.REIScreenHandler; import brachy.modularui.screen.ContainerScreenWrapper; import brachy.modularui.screen.ScreenWrapper; - import brachy.modularui.test.TestRecipeViewerGuis; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; diff --git a/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java b/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java index 322975cd..7e4e912d 100644 --- a/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java +++ b/src/main/java/brachy/modularui/integration/rei/REIStackConverter.java @@ -75,12 +75,14 @@ public EntryIngredient convertTo(EntryList stack, float chance, Unary return null; } dev.architectury.fluid.FluidStack fluidStack = stack.castValue(); - return new FluidStack(fluidStack.getFluid().builtInRegistryHolder(), MathUtils.saturatedCast(fluidStack.getAmount()), + return new FluidStack(fluidStack.getFluid().builtInRegistryHolder(), + MathUtils.saturatedCast(fluidStack.getAmount()), fluidStack.getPatch()); } private static dev.architectury.fluid.FluidStack toREIStack(FluidStack stack) { - return dev.architectury.fluid.FluidStack.create(stack.getFluid(), stack.getAmount(), stack.getComponentsPatch()); + return dev.architectury.fluid.FluidStack.create(stack.getFluid(), stack.getAmount(), + stack.getComponentsPatch()); } private static EntryIngredient toREIIngredient(Stream stream) { @@ -123,12 +125,12 @@ public static Converter getForNullable(Class clazz) { return (Converter) CONVERTERS.get(clazz); } - public static Optional> getFor(Class clazz) { return Optional.ofNullable(getForNullable(clazz)); } - public static EntryIngredient convertToReiEntry(EntryList entries, float chance, UnaryOperator renderMappingFunction) { + public static EntryIngredient convertToReiEntry(EntryList entries, float chance, + UnaryOperator renderMappingFunction) { REIStackConverter.Converter converter = REIStackConverter.getForNullable(entries.getType()); if (converter != null) { return converter.convertTo(entries, chance, renderMappingFunction); diff --git a/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java b/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java index 6dc4135c..30c30805 100644 --- a/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java +++ b/src/main/java/brachy/modularui/integration/rei/ReiRecipeViewerSlot.java @@ -1,16 +1,15 @@ package brachy.modularui.integration.rei; -import net.minecraft.client.Minecraft; -import net.minecraft.world.item.Item; - import brachy.modularui.core.mixins.rei.EntryWidgetAccessor; import brachy.modularui.drawable.TooltipComponentIcon; import brachy.modularui.integration.recipeviewer.RecipeSlotRole; import brachy.modularui.integration.recipeviewer.RecipeViewerSlotWidget; import brachy.modularui.screen.viewport.ModularGuiContext; - import brachy.modularui.theme.WidgetThemeEntry; +import net.minecraft.client.Minecraft; +import net.minecraft.world.item.Item; + import lombok.Getter; import me.shedaniel.math.Point; import me.shedaniel.rei.api.client.gui.widgets.Slot; @@ -24,7 +23,8 @@ public class ReiRecipeViewerSlot extends RecipeViewerSlotWidget ingredientClass) { super(ingredientClass); @@ -33,7 +33,8 @@ public ReiRecipeViewerSlot(Class ingredientClass) { this.tooltipAutoUpdate(true); this.tooltipDynamic(r -> { if (slotWidget != null) { - Tooltip tooltip = slotWidget.getCurrentTooltip(TooltipContext.ofMouse(Item.TooltipContext.of(Minecraft.getInstance().level))); + Tooltip tooltip = slotWidget.getCurrentTooltip( + TooltipContext.ofMouse(Item.TooltipContext.of(Minecraft.getInstance().level))); if (tooltip == null) return; tooltip.entries().forEach(e -> { if (e.isText()) { @@ -63,15 +64,18 @@ protected void rebuildRealSlot() { @Override public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { - this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), context.getRenderPartialTicks()); + this.slotWidget.render(context.getGraphics(), context.getMouseX(), context.getMouseY(), + context.getRenderPartialTicks()); if (this.isHovering() && slotWidget instanceof EntryWidgetAccessor accessor) { - accessor.modularui$invokeDrawHighlighted(context.getGraphics(), context.getMouseX(), context.getMouseY(), context.getRenderPartialTicks()); + accessor.modularui$invokeDrawHighlighted(context.getGraphics(), context.getMouseX(), context.getMouseY(), + context.getRenderPartialTicks()); } } @Override public Result onMousePressed(int button) { - return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? Result.SUCCESS : Result.ACCEPT; + return this.slotWidget.mouseClicked(getContext().getMouseX(), getContext().getMouseY(), button) ? + Result.SUCCESS : Result.ACCEPT; } @Override diff --git a/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java b/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java index 5187dee3..5c6fc82d 100644 --- a/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java +++ b/src/main/java/brachy/modularui/integration/rei/handler/MUIDraggableStackVisitor.java @@ -25,7 +25,6 @@ public MUIDraggableStackVisitor(Class clazz) { this.clazz = clazz; } - @Override public boolean isHandingScreen(R screen) { return clazz.isAssignableFrom(screen.getClass()); diff --git a/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java b/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java index ca7577e6..a6a1984f 100755 --- a/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java +++ b/src/main/java/brachy/modularui/integration/rei/handler/MUIOverlayDecider.java @@ -39,8 +39,8 @@ public InteractionResult shouldScreenBeOverlaid(R screen) { return InteractionResult.PASS; } ModularScreen modularScreen = muiScreen.screen(); - return modularScreen.getContext().getRecipeViewerSettings().isEnabled(modularScreen) ? InteractionResult.SUCCESS : InteractionResult.FAIL; - + return modularScreen.getContext().getRecipeViewerSettings().isEnabled(modularScreen) ? + InteractionResult.SUCCESS : InteractionResult.FAIL; } @Override diff --git a/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java b/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java index 6d4616bc..d231d6d7 100755 --- a/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java +++ b/src/main/java/brachy/modularui/integration/rei/handler/REIScreenHandler.java @@ -30,7 +30,7 @@ import java.util.Map; public class REIScreenHandler extends RecipeViewerHandler - implements DraggableStackProvider, ExclusionZonesProvider { + implements DraggableStackProvider, ExclusionZonesProvider { private static final Map, REIScreenHandler> CACHE = new Reference2ReferenceOpenHashMap<>(); @@ -85,7 +85,7 @@ public static void register(Class clazz, Excl if (converter == null) { return null; } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) var converted = ((REIStackConverter.Converter) converter).convertTo(provider); return new DraggableStack() { diff --git a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java index f4c4e837..345d28ab 100644 --- a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java +++ b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiCategory.java @@ -1,9 +1,9 @@ package brachy.modularui.integration.rei.recipe; -import net.minecraft.network.chat.Component; - import brachy.modularui.integration.recipeviewer.RecipeViewerUtils; +import net.minecraft.network.chat.Component; + import me.shedaniel.math.Rectangle; import me.shedaniel.rei.api.client.gui.widgets.Widget; import me.shedaniel.rei.api.client.registry.display.DisplayCategory; @@ -42,7 +42,9 @@ public int getDisplayHeight(D display) { /** * Return the maximum expected display height here.
- * You should also return a per-category display height that's at most this value in {@link #getDisplayHeight(ModularUIReiDisplay)}. + * You should also return a per-category display height that's at most this value in + * {@link #getDisplayHeight(ModularUIReiDisplay)}. + * * @return The maximum expected display height */ public abstract int getMaxDisplayHeight(); diff --git a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java index ff66f7b5..52727ed0 100644 --- a/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java +++ b/src/main/java/brachy/modularui/integration/rei/recipe/ModularUIReiDisplay.java @@ -42,12 +42,14 @@ public abstract class ModularUIReiDisplay implements Display { private final ResourceLocation recipeId; private final Supplier recipeUI; - @Getter protected final CategoryIdentifier categoryIdentifier; + @Getter + protected final CategoryIdentifier categoryIdentifier; private boolean sizeCalculated = false; private int displayWidth, displayHeight; - public ModularUIReiDisplay(ResourceLocation recipeId, Supplier recipeUI, CategoryIdentifier categoryId) { + public ModularUIReiDisplay(ResourceLocation recipeId, Supplier recipeUI, + CategoryIdentifier categoryId) { this.recipeId = recipeId; this.recipeUI = recipeUI; this.categoryIdentifier = categoryId; @@ -55,7 +57,8 @@ public ModularUIReiDisplay(ResourceLocation recipeId, Supplier recipeUI /** * Calculates the size of the recipe if not already done.
- * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category are calculated + * This should be called in subclasses' constructors. Otherwise, the size of ALL the recipes in the same category + * are calculated * at once, which can make the game lag for a few seconds. */ protected void calculateSize() { @@ -65,7 +68,8 @@ protected void calculateSize() { IWidget ui = this.recipeUI.get(); int w = ui.resizer().getFixedPixelWidth(), h = ui.resizer().getFixedPixelHeight(); if (w < 0 || h < 0) { - ModularScreen screen = createScreen(ui, this.recipeId.getNamespace(), SCREEN_NAME_PREFIX + this.recipeId.getPath()); + ModularScreen screen = createScreen(ui, this.recipeId.getNamespace(), + SCREEN_NAME_PREFIX + this.recipeId.getPath()); w = EmbedHandler.getEmbedWidth(screen); h = EmbedHandler.getEmbedHeight(screen); } @@ -84,7 +88,8 @@ public int getDisplayHeight() { } private ModularScreen createScreen() { - return createScreen(this.recipeUI.get(), this.recipeId.getNamespace(), SCREEN_NAME_PREFIX + this.recipeId.getPath()); + return createScreen(this.recipeUI.get(), this.recipeId.getNamespace(), + SCREEN_NAME_PREFIX + this.recipeId.getPath()); } @ApiStatus.OverrideOnly @@ -155,7 +160,8 @@ public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTi }, () -> { screen.getContext().popMatrix(); }); - Tooltip tooltip = this.getTooltip(TooltipContext.ofMouse(Item.TooltipContext.of(Minecraft.getInstance().level))); + Tooltip tooltip = this + .getTooltip(TooltipContext.ofMouse(Item.TooltipContext.of(Minecraft.getInstance().level))); if (tooltip != null) { tooltip.queue(); } @@ -193,7 +199,7 @@ public List children() { @Override public void mouseMoved(double mouseX, double mouseY) { - //this.screen.mouseMoved(mouseX, mouseY); + // this.screen.mouseMoved(mouseX, mouseY); } @Override diff --git a/src/main/java/brachy/modularui/network/ModularNetwork.java b/src/main/java/brachy/modularui/network/ModularNetwork.java index b49ffb1b..f0cc775b 100644 --- a/src/main/java/brachy/modularui/network/ModularNetwork.java +++ b/src/main/java/brachy/modularui/network/ModularNetwork.java @@ -1,7 +1,6 @@ package brachy.modularui.network; import brachy.modularui.api.IMuiScreen; -import brachy.modularui.api.IPacketWriter; import brachy.modularui.network.packets.SyncHandlerPacket; import brachy.modularui.utils.NetworkUtils; import brachy.modularui.value.sync.ModularSyncManager; @@ -13,7 +12,6 @@ import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.neoforge.network.PacketDistributor; @@ -27,7 +25,8 @@ @ApiStatus.Internal public abstract class ModularNetwork { - // You have to make sure you are choosing the logical side you are currently on otherwise you can mess things up badly, + // You have to make sure you are choosing the logical side you are currently on otherwise you can mess things up + // badly, // since there is no validation. public static final Client CLIENT = new Client(); public static final ServerManager SERVER = new ServerManager(); @@ -121,12 +120,14 @@ public void receivePacket(Player player, SyncHandlerPacket packet) { } @Override - public void sendSyncHandlerPacket(String panel, SyncHandler syncHandler, RegistryFriendlyByteBuf packet, Player player) { + public void sendSyncHandlerPacket(String panel, SyncHandler syncHandler, RegistryFriendlyByteBuf packet, + Player player) { get(player).sendSyncHandlerPacket(panel, syncHandler, packet, player); } @Override - public void sendActionPacket(ModularSyncManager msm, String panel, String key, RegistryFriendlyByteBuf packet, Player player) { + public void sendActionPacket(ModularSyncManager msm, String panel, String key, RegistryFriendlyByteBuf packet, + Player player) { get(player).sendActionPacket(msm, panel, key, packet, player); } diff --git a/src/main/java/brachy/modularui/network/ModularNetworkSide.java b/src/main/java/brachy/modularui/network/ModularNetworkSide.java index 83c624f3..1dca82cf 100644 --- a/src/main/java/brachy/modularui/network/ModularNetworkSide.java +++ b/src/main/java/brachy/modularui/network/ModularNetworkSide.java @@ -1,13 +1,11 @@ package brachy.modularui.network; import brachy.modularui.ModularUI; -import brachy.modularui.api.IPacketWriter; import brachy.modularui.network.packets.CloseAllGuisPacket; import brachy.modularui.network.packets.CloseGuiPacket; import brachy.modularui.network.packets.ReopenGuiPacket; import brachy.modularui.network.packets.SyncHandlerPacket; import brachy.modularui.screen.ModularContainerMenu; -import brachy.modularui.utils.sides.SidedAccessHelper; import brachy.modularui.value.sync.ModularSyncManager; import brachy.modularui.value.sync.SyncHandler; @@ -17,7 +15,6 @@ import net.neoforged.neoforge.common.NeoForge; import net.neoforged.neoforge.event.entity.player.PlayerContainerEvent; -import io.netty.buffer.Unpooled; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; import org.jetbrains.annotations.ApiStatus; @@ -33,7 +30,8 @@ public abstract class ModularNetworkSide { abstract void sendPacket(CustomPacketPayload packet, Player player); void activateInternal(int networkId, ModularSyncManager manager) { - if (activeScreens.containsKey(networkId)) throw new IllegalStateException("Network ID " + networkId + " is already active."); + if (activeScreens.containsKey(networkId)) + throw new IllegalStateException("Network ID " + networkId + " is already active."); activeScreens.put(networkId, manager); inverseActiveScreens.put(manager, networkId); } @@ -76,13 +74,15 @@ public void receivePacket(Player player, SyncHandlerPacket packet) { int id = packet.action() ? 0 : packet.packet().readVarInt(); msm.receiveWidgetUpdate(packet.panel(), packet.key(), packet.action(), id, packet.packet()); } catch (IndexOutOfBoundsException e) { - ModularUI.LOGGER.error("Failed to read packet for sync handler {} in panel {}", packet.key(), packet.panel()); + ModularUI.LOGGER.error("Failed to read packet for sync handler {} in panel {}", packet.key(), + packet.panel()); ModularUI.LOGGER.catching(e); } } @ApiStatus.Internal - public void sendSyncHandlerPacket(String panel, SyncHandler syncHandler, RegistryFriendlyByteBuf packet, Player player) { + public void sendSyncHandlerPacket(String panel, SyncHandler syncHandler, RegistryFriendlyByteBuf packet, + Player player) { ModularSyncManager msm = syncHandler.getSyncManager().getModularSyncManager(); if (!inverseActiveScreens.containsKey(msm)) return; int id = inverseActiveScreens.getInt(msm); @@ -90,7 +90,8 @@ public void sendSyncHandlerPacket(String panel, SyncHandler syncHandler, Regi } @ApiStatus.Internal - public void sendActionPacket(ModularSyncManager msm, String panel, String key, RegistryFriendlyByteBuf packet, Player player) { + public void sendActionPacket(ModularSyncManager msm, String panel, String key, RegistryFriendlyByteBuf packet, + Player player) { if (!inverseActiveScreens.containsKey(msm)) return; int id = inverseActiveScreens.getInt(msm); sendPacket(new SyncHandlerPacket(id, panel, key, true, packet), player); diff --git a/src/main/java/brachy/modularui/network/packets/OpenGuiPacket.java b/src/main/java/brachy/modularui/network/packets/OpenGuiPacket.java index 9f3396da..49370cc6 100644 --- a/src/main/java/brachy/modularui/network/packets/OpenGuiPacket.java +++ b/src/main/java/brachy/modularui/network/packets/OpenGuiPacket.java @@ -15,7 +15,8 @@ import net.minecraft.server.level.ServerPlayer; import net.neoforged.neoforge.network.handling.IPayloadContext; -public record OpenGuiPacket(int windowId, int networkId, UIFactory factory, RegistryFriendlyByteBuf data) +public record OpenGuiPacket(int windowId, int networkId, UIFactory factory, + RegistryFriendlyByteBuf data) implements CustomPacketPayload { public static final ResourceLocation ID = ModularUI.id("open_gui"); diff --git a/src/main/java/brachy/modularui/overlay/DebugOverlay.java b/src/main/java/brachy/modularui/overlay/DebugOverlay.java index 01f5e1e3..00fadbfc 100644 --- a/src/main/java/brachy/modularui/overlay/DebugOverlay.java +++ b/src/main/java/brachy/modularui/overlay/DebugOverlay.java @@ -117,7 +117,8 @@ public DebugOverlay(IMuiScreen screen) { .child(toggleOption(10, "Any", "showParent")) .child(toggleOption(11, "Pos", "showParentPos")) .child(toggleOption(12, "Size", "showParentSize")) - .child(toggleOption(13, "Widget Theme", "showParentWidgetTheme")) + .child(toggleOption(13, "Widget Theme", + "showParentWidgetTheme")) .child(toggleOption(14, "Outline", "showParentOutline"))))))); } diff --git a/src/main/java/brachy/modularui/overlay/OverlayStack.java b/src/main/java/brachy/modularui/overlay/OverlayStack.java index d5851d3f..146f9d0a 100644 --- a/src/main/java/brachy/modularui/overlay/OverlayStack.java +++ b/src/main/java/brachy/modularui/overlay/OverlayStack.java @@ -9,10 +9,10 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; import net.neoforged.neoforge.common.NeoForge; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/brachy/modularui/screen/BuildPanelEvent.java b/src/main/java/brachy/modularui/screen/BuildPanelEvent.java index 5a8d5172..544f7ba4 100644 --- a/src/main/java/brachy/modularui/screen/BuildPanelEvent.java +++ b/src/main/java/brachy/modularui/screen/BuildPanelEvent.java @@ -11,14 +11,18 @@ * An event that is invoked after a panel has been build. * Sub panels can be completely replaced using the {@link SubPanel sub panel event}. * Main panels can not be replaced, but it's children can be by using - * {@link brachy.modularui.api.widget.IWidget#visitTransformAllChildren(UnaryOperator) IWidget.visitTransformAllChildren(UnaryOperator)}. + * {@link brachy.modularui.api.widget.IWidget#visitTransformAllChildren(UnaryOperator) + * IWidget.visitTransformAllChildren(UnaryOperator)}. */ @ApiStatus.NonExtendable public class BuildPanelEvent extends Event { - @Getter private final ModularScreen screen; - @Getter private final ModularPanel mainPanel; - @Getter protected ModularPanel openingPanel; + @Getter + private final ModularScreen screen; + @Getter + private final ModularPanel mainPanel; + @Getter + protected ModularPanel openingPanel; protected BuildPanelEvent(ModularScreen screen, ModularPanel openingPanel) { this.screen = screen; @@ -47,7 +51,8 @@ public boolean matches(String screenOwner, String mainPanel) { } public boolean matches(String screenOwner, String mainPanel, String openingPanel) { - return getScreenName().equals(screenOwner) && getMainPanelName().equals(mainPanel) && getOpeningPanelName().equals(openingPanel); + return getScreenName().equals(screenOwner) && getMainPanelName().equals(mainPanel) && + getOpeningPanelName().equals(openingPanel); } public static final class MainPanel extends BuildPanelEvent { diff --git a/src/main/java/brachy/modularui/screen/ClientScreenHandler.java b/src/main/java/brachy/modularui/screen/ClientScreenHandler.java index 6086e19f..a8138a3b 100644 --- a/src/main/java/brachy/modularui/screen/ClientScreenHandler.java +++ b/src/main/java/brachy/modularui/screen/ClientScreenHandler.java @@ -45,9 +45,6 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.HitResult; -import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; import net.neoforged.api.distmarker.Dist; import net.neoforged.bus.api.EventPriority; import net.neoforged.bus.api.SubscribeEvent; @@ -59,6 +56,9 @@ import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; import net.neoforged.neoforge.common.NeoForge; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; @@ -111,8 +111,9 @@ public static void onInitScreenPost(ScreenEvent.Init.Post event) { OverlayStack.foreach(ms -> ms.onResize(event.getScreen().width, event.getScreen().height), false); } - // TODO: Figure out when exactly early inputs (before recipe viewer) for mouse press, mouse release, key press, key release, - // mouse scroll and mouse drag are needed. One case would may be draggable widgets. + // TODO: Figure out when exactly early inputs (before recipe viewer) for mouse press, mouse release, key press, key + // release, + // mouse scroll and mouse drag are needed. One case would may be draggable widgets. @SubscribeEvent public static void onScreenKeyPressedHigh(ScreenEvent.KeyPressed.Pre event) { defaultContext.updateKey(event.getKeyCode(), event.getScanCode(), event.getModifiers(), true); @@ -373,7 +374,8 @@ private static boolean keyTyped(Screen screen, int keyCode, int scanCode, int mo } if (!hasLevel) return false; // E only closes in world if (Minecraft.getInstance().options.keyInventory - .isActiveAndMatches(InputConstants.getKey(keyCode, scanCode)) && !RecipeViewerHandler.getCurrent().isSearchFocused()) { + .isActiveAndMatches(InputConstants.getKey(keyCode, scanCode)) && + !RecipeViewerHandler.getCurrent().isSearchFocused()) { dropOrClosePanel(); return true; } @@ -449,7 +451,8 @@ public static void drawScreen(GuiGraphics graphics, ModularScreen muiScreen, Scr } } - public static void drawScreenInternal(GuiGraphics graphics, ModularScreen muiScreen, Screen mcScreen, int mouseX, int mouseY, float partialTicks) { + public static void drawScreenInternal(GuiGraphics graphics, ModularScreen muiScreen, Screen mcScreen, int mouseX, + int mouseY, float partialTicks) { Stencil.reset(); muiScreen.getContext().reset(); muiScreen.getContext().getStencil().push(muiScreen.getScreenArea()); @@ -554,12 +557,14 @@ private static void drawFloatingItemStack(AbstractContainerScreen mcScreen, G } @ApiStatus.Internal - public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, float partialTicks) { + public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, + float partialTicks) { drawVanillaElements(graphics, mcScreen, mouseX, mouseY, partialTicks, r -> true); } @ApiStatus.Internal - public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, float partialTicks, Predicate filter) { + public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, int mouseX, int mouseY, + float partialTicks, Predicate filter) { for (Renderable renderable : mcScreen.renderables) { if (filter.test(renderable)) { renderable.render(graphics, mouseX, mouseY, partialTicks); @@ -567,7 +572,8 @@ public static void drawVanillaElements(GuiGraphics graphics, Screen mcScreen, in } } - public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen muiScreen, @Nullable ModularScreen fallback) { + public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen muiScreen, + @Nullable ModularScreen fallback) { fpsCounter.onDraw(); if (!ModularUIConfig.Dev.debugUI()) return; if (muiScreen == null) { @@ -586,8 +592,10 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen int mouseX = context.getAbsMouseX(), mouseY = context.getAbsMouseY(); int screenH = muiScreen.getScreenArea().height; - int outlineColor = Color.parseString(ModularUIConfig.DEBUG_OUTLINE_COLOR.get(), DEFAULT_DEBUG_OUTLINE_COLOR).resultOrPartial(s -> {}).orElseThrow(); - int textColor = Color.parseString(ModularUIConfig.DEBUG_TEXT_COLOR.get(), DEFAULT_DEBUG_TEXT_COLOR).resultOrPartial(s -> {}).orElseThrow(); + int outlineColor = Color.parseString(ModularUIConfig.DEBUG_OUTLINE_COLOR.get(), DEFAULT_DEBUG_OUTLINE_COLOR) + .resultOrPartial(s -> {}).orElseThrow(); + int textColor = Color.parseString(ModularUIConfig.DEBUG_TEXT_COLOR.get(), DEFAULT_DEBUG_TEXT_COLOR) + .resultOrPartial(s -> {}).orElseThrow(); float scale = ModularUIConfig.Dev.scale(); int shift = (int) (11 * scale + 0.5f); int lineY = screenH - shift - 2; @@ -639,7 +647,8 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen locatedHovered.unapplyMatrix(context); if (showHovered) { if (ModularUIConfig.Dev.showWidgetTheme()) { - s = I18n.get("modularui.debug.widget_theme_key", hovered.getWidgetThemeEntry(hovered.getTheme()).key().getFullName()); + s = I18n.get("modularui.debug.widget_theme_key", + hovered.getWidgetThemeEntry(hovered.getTheme()).key().getFullName()); GuiDraw.drawText(graphics, s, 5, lineY, scale, textColor, true); lineY -= shift; } @@ -662,7 +671,8 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen lineY -= 10; } if (ModularUIConfig.Dev.showParentWidgetTheme()) { - s = I18n.get("modularui.debug.widget_theme_key", parent.getWidgetThemeEntry(parent.getTheme()).key().getFullName()); + s = I18n.get("modularui.debug.widget_theme_key", + parent.getWidgetThemeEntry(parent.getTheme()).key().getFullName()); GuiDraw.drawText(graphics, s, 5, lineY, scale, textColor, true); lineY -= shift; } @@ -694,7 +704,8 @@ public static void drawDebugScreen(GuiGraphics graphics, @Nullable ModularScreen if (slotWidget.isSynced()) { SlotGroup slotGroup = slot.getSlotGroup(); boolean allowShiftTransfer = slotGroup != null && slotGroup.isAllowShiftTransfer(); - s = I18n.get("modularui.debug.shift_click_priority", allowShiftTransfer ? slotGroup.getShiftClickPriority() : "DISABLED"); + s = I18n.get("modularui.debug.shift_click_priority", + allowShiftTransfer ? slotGroup.getShiftClickPriority() : "DISABLED"); GuiDraw.drawText(graphics, s, 5, lineY, scale, textColor, true); } } else if (hovered instanceof RichTextWidget richTextWidget) { diff --git a/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java b/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java index b91e555a..5d50d0b6 100755 --- a/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java +++ b/src/main/java/brachy/modularui/screen/ContainerScreenWrapper.java @@ -31,7 +31,7 @@ public ContainerScreenWrapper(ModularContainerMenu container, @NotNull ModularSc * * @deprecated Internal use only. */ - @SuppressWarnings({"DataFlowIssue", "DeprecatedIsStillUsed"}) + @SuppressWarnings({ "DataFlowIssue", "DeprecatedIsStillUsed" }) @Deprecated @ApiStatus.Internal public ContainerScreenWrapper(ModularContainerMenu container, Inventory playerInventory, Component title) { diff --git a/src/main/java/brachy/modularui/screen/EmbedHandler.java b/src/main/java/brachy/modularui/screen/EmbedHandler.java index 7c229a23..73b9ea43 100644 --- a/src/main/java/brachy/modularui/screen/EmbedHandler.java +++ b/src/main/java/brachy/modularui/screen/EmbedHandler.java @@ -5,15 +5,12 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.Renderable; import net.minecraft.client.gui.screens.Screen; + import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; - import org.jetbrains.annotations.Nullable; -import java.util.function.Predicate; - public class EmbedHandler { public static int getEmbedWidth(ModularScreen screen) { @@ -24,7 +21,8 @@ public static int getEmbedHeight(ModularScreen screen) { return screen.getMainPanel().getArea().height; } - public static void drawEmbed(ModularScreen screen, GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + public static void drawEmbed(ModularScreen screen, GuiGraphics graphics, int mouseX, int mouseY, + float partialTicks) { drawEmbed(screen, graphics, mouseX, mouseY, partialTicks, null, null); } diff --git a/src/main/java/brachy/modularui/screen/ModularContainerMenu.java b/src/main/java/brachy/modularui/screen/ModularContainerMenu.java index d7b7a17d..5d9f1a6f 100644 --- a/src/main/java/brachy/modularui/screen/ModularContainerMenu.java +++ b/src/main/java/brachy/modularui/screen/ModularContainerMenu.java @@ -19,10 +19,10 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.InputConstants; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.blaze3d.platform.InputConstants; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; @@ -63,14 +63,16 @@ public ModularContainerMenu(int containerId) { super(ModularUIMenuTypes.MODULAR_CONTAINER.get(), containerId); } - public ModularContainerMenu(int containerId, Inventory playerInv, @Nullable FriendlyByteBuf data) { + public ModularContainerMenu(int containerId, Inventory playerInv, + @Nullable FriendlyByteBuf data) { this(containerId); // TODO: Better integration with menu types for custom containers and screens. throw new IllegalArgumentException("Do not open the modular container the forge way. Use an UIFactory!"); } @ApiStatus.Internal - public void construct(Player player, ModularSyncManager msm, UISettings settings, String mainPanelName, GuiData guiData) { + public void construct(Player player, ModularSyncManager msm, UISettings settings, String mainPanelName, + GuiData guiData) { this.player = player; this.syncManager = msm; this.syncManager.construct(this, mainPanelName); @@ -170,7 +172,8 @@ public void registerSlot(String panelName, ModularSlot slot) { if (slot.getSlotGroupName() != null) { SlotGroup slotGroup = getSyncManager().getSlotGroup(panelName, slot.getSlotGroupName()); if (slotGroup == null) { - ModularUI.LOGGER.throwing(new IllegalArgumentException("SlotGroup '" + slot.getSlotGroupName() + "' is not registered!")); + ModularUI.LOGGER.throwing( + new IllegalArgumentException("SlotGroup '" + slot.getSlotGroupName() + "' is not registered!")); return; } slot.slotGroup(slotGroup); @@ -189,7 +192,8 @@ public void registerSlot(String panelName, ModularSlot slot) { @Contract("_, null, null -> fail") @NotNull @ApiStatus.Internal - public SlotGroup validateSlotGroup(String panelName, @Nullable String slotGroupName, @Nullable SlotGroup slotGroup) { + public SlotGroup validateSlotGroup(String panelName, @Nullable String slotGroupName, + @Nullable SlotGroup slotGroup) { if (slotGroup != null) { if (getSyncManager().getSlotGroup(panelName, slotGroup.getName()) == null) { throw new IllegalArgumentException("Slot group is not registered in the GUI."); @@ -324,19 +328,19 @@ public void clicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, } } else if (heldStack.getMaxStackSize() > 1 && ItemStack.isSameItemSameComponents(slotStack, heldStack) && !slotStack.isEmpty()) { - int stackCount = slotStack.getCount(); + int stackCount = slotStack.getCount(); - if (stackCount + heldStack.getCount() <= heldStack.getMaxStackSize()) { - heldStack.grow(stackCount); - slotStack = clickedSlot.remove(stackCount); + if (stackCount + heldStack.getCount() <= heldStack.getMaxStackSize()) { + heldStack.grow(stackCount); + slotStack = clickedSlot.remove(stackCount); - if (slotStack.isEmpty()) { - clickedSlot.setByPlayer(ItemStack.EMPTY); - } + if (slotStack.isEmpty()) { + clickedSlot.setByPlayer(ItemStack.EMPTY); + } - clickedSlot.onTake(player, this.getCarried()); - } - } + clickedSlot.onTake(player, this.getCarried()); + } + } } clickedSlot.setChanged(); } @@ -352,7 +356,8 @@ public void clicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, int step = mouseButton == InputConstants.MOUSE_BUTTON_LEFT ? 1 : -1; for (int i = 0; i < 2; ++i) { - for (int s = start; s >= 0 && s < slots.size() && carried.getCount() < carried.getMaxStackSize(); s += step) { + for (int s = start; s >= 0 && s < slots.size() && + carried.getCount() < carried.getMaxStackSize(); s += step) { Slot current = slots.get(s); if (current instanceof ModularSlot modularSlot && modularSlot.isPhantom()) continue; @@ -381,80 +386,85 @@ public void clicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, broadcastChanges(); } else if (clickTypeIn == ClickType.SWAP && ((mouseButton >= 0 && mouseButton < 9) || mouseButton == Inventory.SLOT_OFFHAND)) { - // minecraft does not check if the hotbar slot can actually take and put items - Slot hotbarSlot = findPlayerSlot(player, mouseButton); // mouseButton is the slot index here - if (hotbarSlot == null && mouseButton == Inventory.SLOT_OFFHAND) { - // the offhand is usually not bound as a slot, but it still needs to respect stack size limits - hotbarSlot = new Slot(inventory, Inventory.SLOT_OFFHAND, 0, 0); - } - if (hotbarSlot != null && slotId >= 0) { - Slot fromSlot = getSlot(slotId); - ItemStack fromStack = fromSlot.getItem().copy(); - ItemStack hotbarStack = hotbarSlot.getItem().copy(); - - if (!fromStack.isEmpty() && !hotbarSlot.mayPlace(fromStack)) return; - if (!hotbarStack.isEmpty() && !fromSlot.mayPlace(hotbarStack)) return; - if (!fromStack.isEmpty() && !fromSlot.mayPickup(player)) return; - if (!hotbarStack.isEmpty() && !hotbarSlot.mayPickup(player)) return; - - if (!fromStack.isEmpty() && !hotbarStack.isEmpty() && ItemStack.isSameItemSameComponents(fromStack, hotbarStack)) { - int hotbarLimit = hotbarSlot.getMaxStackSize(fromStack); - if (hotbarStack.getCount() < hotbarLimit) { - int toMove = Math.min(fromStack.getCount(), hotbarLimit - hotbarStack.getCount()); - hotbarStack.grow(toMove); - fromStack.shrink(toMove); - hotbarSlot.set(hotbarStack); - fromSlot.set(fromStack); + // minecraft does not check if the hotbar slot can actually take and put items + Slot hotbarSlot = findPlayerSlot(player, mouseButton); // mouseButton is the slot index here + if (hotbarSlot == null && mouseButton == Inventory.SLOT_OFFHAND) { + // the offhand is usually not bound as a slot, but it still needs to respect stack size limits + hotbarSlot = new Slot(inventory, Inventory.SLOT_OFFHAND, 0, 0); + } + if (hotbarSlot != null && slotId >= 0) { + Slot fromSlot = getSlot(slotId); + ItemStack fromStack = fromSlot.getItem().copy(); + ItemStack hotbarStack = hotbarSlot.getItem().copy(); + + if (!fromStack.isEmpty() && !hotbarSlot.mayPlace(fromStack)) return; + if (!hotbarStack.isEmpty() && !fromSlot.mayPlace(hotbarStack)) return; + if (!fromStack.isEmpty() && !fromSlot.mayPickup(player)) return; + if (!hotbarStack.isEmpty() && !hotbarSlot.mayPickup(player)) return; + + if (!fromStack.isEmpty() && !hotbarStack.isEmpty() && + ItemStack.isSameItemSameComponents(fromStack, hotbarStack)) { + int hotbarLimit = hotbarSlot.getMaxStackSize(fromStack); + if (hotbarStack.getCount() < hotbarLimit) { + int toMove = Math.min(fromStack.getCount(), hotbarLimit - hotbarStack.getCount()); + hotbarStack.grow(toMove); + fromStack.shrink(toMove); + hotbarSlot.set(hotbarStack); + fromSlot.set(fromStack); + } + return; + } + boolean canFitInHotbar = fromStack.isEmpty() || + fromStack.getCount() <= hotbarSlot.getMaxStackSize(fromStack); + boolean canFitInFromSlot = hotbarStack.isEmpty() || + hotbarStack.getCount() <= fromSlot.getMaxStackSize(hotbarStack); + + if (canFitInHotbar && canFitInFromSlot) { + fromSlot.setByPlayer(hotbarStack); + hotbarSlot.setByPlayer(fromStack); + fromSlot.onTake(player, fromStack); + return; + } + if (hotbarStack.isEmpty() && !fromStack.isEmpty()) { + int moveAmt = hotbarSlot.getMaxStackSize(fromStack); + hotbarStack = fromStack.copyWithCount(moveAmt); + fromStack.shrink(moveAmt); + fromSlot.set(fromStack); + hotbarSlot.setByPlayer(hotbarStack); + } else if (fromStack.isEmpty() && !hotbarStack.isEmpty()) { + int moveAmt = fromSlot.getMaxStackSize(hotbarStack); + fromStack = hotbarStack.copyWithCount(moveAmt); + hotbarStack.shrink(moveAmt); + fromSlot.setByPlayer(fromStack); + hotbarSlot.set(hotbarStack); + } + } + } else + if (clickTypeIn == ClickType.THROW && getCarried().isEmpty() && slotId >= 0) { + Slot slot = getSlot(slotId); + + if (slot.hasItem() && slot.mayPickup(player)) { + ItemStack stackInSlot = slot.getItem().copy(); + int amountToDrop = 1; + // mouseButton 1 is CTRL+Q + if (mouseButton == 1) { + amountToDrop = Math.min(stackInSlot.getCount(), stackInSlot.getMaxStackSize()); } - return; - } - boolean canFitInHotbar = fromStack.isEmpty() || fromStack.getCount() <= hotbarSlot.getMaxStackSize(fromStack); - boolean canFitInFromSlot = hotbarStack.isEmpty() || hotbarStack.getCount() <= fromSlot.getMaxStackSize(hotbarStack); - - if (canFitInHotbar && canFitInFromSlot) { - fromSlot.setByPlayer(hotbarStack); - hotbarSlot.setByPlayer(fromStack); - fromSlot.onTake(player, fromStack); - return; - } - if (hotbarStack.isEmpty() && !fromStack.isEmpty()) { - int moveAmt = hotbarSlot.getMaxStackSize(fromStack); - hotbarStack = fromStack.copyWithCount(moveAmt); - fromStack.shrink(moveAmt); - fromSlot.set(fromStack); - hotbarSlot.setByPlayer(hotbarStack); - } else if (fromStack.isEmpty() && !hotbarStack.isEmpty()) { - int moveAmt = fromSlot.getMaxStackSize(hotbarStack); - fromStack = hotbarStack.copyWithCount(moveAmt); - hotbarStack.shrink(moveAmt); - fromSlot.setByPlayer(fromStack); - hotbarSlot.set(hotbarStack); - } - } - } else if (clickTypeIn == ClickType.THROW && getCarried().isEmpty() && slotId >= 0) { - Slot slot = getSlot(slotId); - - if (slot.hasItem() && slot.mayPickup(player)) { - ItemStack stackInSlot = slot.getItem().copy(); - int amountToDrop = 1; - // mouseButton 1 is CTRL+Q - if (mouseButton == 1) { - amountToDrop = Math.min(stackInSlot.getCount(), stackInSlot.getMaxStackSize()); - } - if (amountToDrop > 0) { - ItemStack droppedStack = stackInSlot.copyWithCount(amountToDrop); - stackInSlot.shrink(amountToDrop); - slot.set(stackInSlot); - player.drop(droppedStack, true); + if (amountToDrop > 0) { + ItemStack droppedStack = stackInSlot.copyWithCount(amountToDrop); + stackInSlot.shrink(amountToDrop); + slot.set(stackInSlot); + player.drop(droppedStack, true); + } } + } else { + superClicked(slotId, mouseButton, clickTypeIn, player); } - } else { - superClicked(slotId, mouseButton, clickTypeIn, player); - } } - protected final void superClicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, @NotNull Player player) { + protected final void superClicked(int slotId, int mouseButton, @NotNull ClickType clickTypeIn, + @NotNull Player player) { super.clicked(slotId, mouseButton, clickTypeIn, player); } @@ -508,7 +518,8 @@ protected Slot findExternalPlayerSlot(Player player, int index) { slot.onTake(playerIn, remainder); slot.onCraftShiftClick(playerIn, remainder); - return copy; // return a non-empty stack if insertion was successful, this causes this function to be called again, important for crafting + return copy; // return a non-empty stack if insertion was successful, this causes this function to be + // called again, important for crafting } } return ItemStack.EMPTY; @@ -522,7 +533,8 @@ protected ItemStack transferItem(ModularSlot fromSlot, ItemStack fromStack) { SlotGroup slotGroup = Objects.requireNonNull(toSlot.getSlotGroup()); if (slotGroup != fromSlotGroup && toSlot.isActive() && toSlot.mayPlace(fromStack)) { ItemStack toStack = toSlot.getItem().copy(); - if (!fromSlot.isPhantom() && !toSlot.isPhantom() && ItemStack.isSameItemSameComponents(fromStack, toStack)) { + if (!fromSlot.isPhantom() && !toSlot.isPhantom() && + ItemStack.isSameItemSameComponents(fromStack, toStack)) { int j = toStack.getCount() + fromStack.getCount(); // Math.min(toSlot.getMaxStackSize(), fromStack.getMaxStackSize()); int maxSize = toSlot.getMaxStackSize(fromStack); diff --git a/src/main/java/brachy/modularui/screen/ModularPanel.java b/src/main/java/brachy/modularui/screen/ModularPanel.java index a70b1567..2c79f73e 100644 --- a/src/main/java/brachy/modularui/screen/ModularPanel.java +++ b/src/main/java/brachy/modularui/screen/ModularPanel.java @@ -52,7 +52,8 @@ * This class is like a window in windows. It can hold any amount of widgets. It may also be draggable.
* To open another panel on top of the main panel you must use * {@link IPanelHandler#simple(ModularPanel, SecondaryPanel.IPanelBuilder, boolean)} - * or {@link PanelSyncManager#syncedPanel(String, boolean, PanelSyncHandler.IPanelBuilder)} if the panel should be synced. + * or {@link PanelSyncManager#syncedPanel(String, boolean, PanelSyncHandler.IPanelBuilder)} if the panel should be + * synced. */ public class ModularPanel> extends ParentWidget implements IViewport, IDragResizeable { @@ -99,7 +100,8 @@ public static ModularPanel defaultPanel(@NotNull String name, int width, int /** * True if this panel can be dragged. Never works on the main panel. */ - @Getter private boolean draggable = true; + @Getter + private boolean draggable = true; private boolean disablePanelsBelow = false; private boolean closeOnOutOfBoundsClick = false; @@ -177,7 +179,8 @@ public void closeIfOpen() { } getAnimator().onFinish(() -> { if (this.screen != null) { - // can happen when multiple panels close at once and animation is enabled, but NEA is currently not ported so screen + // can happen when multiple panels close at once and animation is enabled, but NEA is currently not + // ported so screen // before sub panels can finish animating this.screen.getPanelManager().closePanel(this); } @@ -287,7 +290,8 @@ public void onClose() { @Override public boolean isExcludeAreaInRecipeViewer() { - return super.isExcludeAreaInRecipeViewer() || (!getScreen().isOverlay() && !this.invisible && !resizer().isFullSize()); + return super.isExcludeAreaInRecipeViewer() || + (!getScreen().isOverlay() && !this.invisible && !resizer().isFullSize()); } @MustBeInvokedByOverriders diff --git a/src/main/java/brachy/modularui/screen/ModularScreen.java b/src/main/java/brachy/modularui/screen/ModularScreen.java index d81889ff..ba08f7b7 100644 --- a/src/main/java/brachy/modularui/screen/ModularScreen.java +++ b/src/main/java/brachy/modularui/screen/ModularScreen.java @@ -29,14 +29,14 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.neoforge.common.NeoForge; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -102,7 +102,8 @@ public static ModularScreen createEmbed(String owner, ModularPanel panel, int /** * The owner of this screen. Usually a modid. This is mainly used to find theme overrides. */ - @Getter private final String owner; + @Getter + private final String owner; /** * The name of this screen, which is also the name of the panel. Every UI under one owner should have a different * name. @@ -110,24 +111,32 @@ public static ModularScreen createEmbed(String owner, ModularPanel panel, int * name for the main panel. * This is mainly used to find theme overrides. */ - @Getter private final String name; - @Getter private final PanelManager panelManager; - @Getter private final ModularGuiContext context; + @Getter + private final String name; + @Getter + private final PanelManager panelManager; + @Getter + private final ModularGuiContext context; private final Map, List> guiActionListeners = new Object2ObjectOpenHashMap<>(); private final Object2ObjectArrayMap frameUpdates = new Object2ObjectArrayMap<>(); - @Getter private final ScreenResizeNode resizeNode = new ScreenResizeNode(this); - @Getter private boolean pauseScreen = false; - @Getter private boolean openParentOnClose = false; + @Getter + private final ScreenResizeNode resizeNode = new ScreenResizeNode(this); + @Getter + private boolean pauseScreen = false; + @Getter + private boolean openParentOnClose = false; @Getter @Nullable private String themeOverride; private ITheme currentTheme; - @Getter private IMuiScreen screenWrapper; + @Getter + private IMuiScreen screenWrapper; /** * true if this is an overlay for another screen */ - @Getter private boolean overlay = false; + @Getter + private boolean overlay = false; private double lastUpdate = -1, lastFrameUpdate = -1; @@ -148,14 +157,17 @@ public ModularScreen(@NotNull String owner, @NotNull ModularPanel mainPanel) * @param mainPanelCreator function which creates the main panel of this screen */ public ModularScreen(String owner, @NotNull Function> mainPanelCreator) { - this(UIType.MODULAR_SCREEN, owner, Objects.requireNonNull(mainPanelCreator, "The main panel function must not be null!"), false); + this(UIType.MODULAR_SCREEN, owner, + Objects.requireNonNull(mainPanelCreator, "The main panel function must not be null!"), false); } - private ModularScreen(UIType uiType, String owner, @Nullable Function> mainPanelCreator, boolean __) { + private ModularScreen(UIType uiType, String owner, + @Nullable Function> mainPanelCreator, boolean __) { this.context = new ModularGuiContext(Objects.requireNonNull(uiType, "UIType must not be null"), this); Objects.requireNonNull(owner, "The owner must not be null!"); this.owner = owner; - ModularPanel mainPanel = mainPanelCreator != null ? mainPanelCreator.apply(this.context) : buildUI(this.context); + ModularPanel mainPanel = mainPanelCreator != null ? mainPanelCreator.apply(this.context) : + buildUI(this.context); Objects.requireNonNull(mainPanel, "The main panel must not be null!"); this.name = mainPanel.getName(); this.panelManager = new PanelManager(this, mainPanel); @@ -314,7 +326,7 @@ public void onUpdate() { public void onFrameUpdate() { this.panelManager.checkDirty(); for (ObjectIterator> iterator = this.frameUpdates - .object2ObjectEntrySet().fastIterator(); iterator.hasNext(); ) { + .object2ObjectEntrySet().fastIterator(); iterator.hasNext();) { Object2ObjectMap.Entry entry = iterator.next(); if (!entry.getKey().isValid()) { iterator.remove(); @@ -589,7 +601,8 @@ public boolean mouseScrolled(double deltaX, double deltaY) { * Interactable#onMouseDrag(double, double, int, double, double)} on every widget * under the mouse after gui action listeners have been called. * - * @param button mouse button that is held down (0 = left button, 1 = right button, 2 = scroll button, 4 and 5 = side buttons) + * @param button mouse button that is held down (0 = left button, 1 = right button, 2 = scroll button, 4 and 5 = + * side buttons) * @param dragX the X distance of the drag * @param dragY the Y distance of the drag * @return true if the action was consumed and further processing should be canceled @@ -665,8 +678,8 @@ public Area getScreenArea() { } public boolean isClientOnly() { - return isOverlay() || getContext().getUIType() != UIType.MODULAR_SCREEN - || !this.screenWrapper.isContainerScreen() || getContainer().isClientOnly(); + return isOverlay() || getContext().getUIType() != UIType.MODULAR_SCREEN || + !this.screenWrapper.isContainerScreen() || getContainer().isClientOnly(); } public ModularContainerMenu getContainer() { diff --git a/src/main/java/brachy/modularui/screen/PanelManager.java b/src/main/java/brachy/modularui/screen/PanelManager.java index e662bb1b..deee254b 100644 --- a/src/main/java/brachy/modularui/screen/PanelManager.java +++ b/src/main/java/brachy/modularui/screen/PanelManager.java @@ -216,7 +216,8 @@ public void closeTopPanel() { } /** - * Closes all panels. Note that this won't close the screen and can put the screen and main panel into an invalid state if used + * Closes all panels. Note that this won't close the screen and can put the screen and main panel into an invalid + * state if used * incorrectly. Use {@link #closePanelsAndScreen()} to actually close all panels and the screen properly. * * @return if the screen was open diff --git a/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java b/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java index 189c2413..df663300 100644 --- a/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java +++ b/src/main/java/brachy/modularui/screen/RecipeViewerSettingsImpl.java @@ -155,7 +155,7 @@ public List> getGhostIngredientSlots() { public List getAllExclusionAreas() { this.exclusionWidgets.removeIf(widget -> !widget.isValid()); List areas = new ArrayList<>(this.exclusionAreas); - for (Iterator iterator = this.exclusionWidgets.iterator(); iterator.hasNext(); ) { + for (Iterator iterator = this.exclusionWidgets.iterator(); iterator.hasNext();) { IWidget widget = iterator.next(); if (!widget.isValid()) { iterator.remove(); diff --git a/src/main/java/brachy/modularui/screen/RichTooltip.java b/src/main/java/brachy/modularui/screen/RichTooltip.java index e9914a8c..799d4951 100644 --- a/src/main/java/brachy/modularui/screen/RichTooltip.java +++ b/src/main/java/brachy/modularui/screen/RichTooltip.java @@ -27,14 +27,14 @@ import net.minecraft.util.StringRepresentable; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.serialization.Codec; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.neoforge.client.event.RenderTooltipEvent; import net.neoforged.neoforge.common.NeoForge; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.serialization.Codec; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -72,11 +72,13 @@ public class RichTooltip implements IRichTextBuilder { @Getter @Setter private boolean autoUpdate = false; - @Getter private int titleMargin = 0; + @Getter + private int titleMargin = 0; private boolean appliedMargin = true; private int x = 0, y = 0; - @Getter private int maxWidth = Integer.MAX_VALUE; + @Getter + private int maxWidth = Integer.MAX_VALUE; private boolean dirty; @@ -156,22 +158,26 @@ public void draw(GuiContext context, ItemStack stack) { RichText copy = this.text.copy(); // rich event to gather additional tooltip // this does not trigger vanilla event listeners - var richGatherEventPre = new RichTooltipEvent.Gather.Pre(copy, stack, context, mouseX, mouseY, screen.width, screen.height, this.maxWidth); + var richGatherEventPre = new RichTooltipEvent.Gather.Pre(copy, stack, context, mouseX, mouseY, screen.width, + screen.height, this.maxWidth); if (NeoForge.EVENT_BUS.post(richGatherEventPre).isCanceled()) return; this.maxWidth = richGatherEventPre.getMaxWidth(); // vanilla event to gather additional tooltip TooltipLines textLines = copy.getAsText(); - // wrap the List> in the type vanilla wants. Listeners may add any FormattedText, - // which the wrapper converts into Components. + // wrap the List> in the type vanilla wants. Listeners may add any + // FormattedText, + // which the wrapper converts into Components. // noinspection UnstableApiUsage - var vanillaGatherEvent = new RenderTooltipEvent.GatherComponents(stack, screen.width, screen.height, textLines.vanillaElementHandler(), this.maxWidth); + var vanillaGatherEvent = new RenderTooltipEvent.GatherComponents(stack, screen.width, screen.height, + textLines.vanillaElementHandler(), this.maxWidth); if (NeoForge.EVENT_BUS.post(vanillaGatherEvent).isCanceled()) return; this.maxWidth = vanillaGatherEvent.getMaxWidth(); // rich event to gather additional tooltip // this does not trigger vanilla event listeners - var richGatherEventPost = new RichTooltipEvent.Gather.Post(copy, stack, context, mouseX, mouseY, screen.width, screen.height, this.maxWidth); + var richGatherEventPost = new RichTooltipEvent.Gather.Post(copy, stack, context, mouseX, mouseY, screen.width, + screen.height, this.maxWidth); if (NeoForge.EVENT_BUS.post(richGatherEventPost).isCanceled()) return; this.maxWidth = richGatherEventPost.getMaxWidth(); @@ -461,8 +467,8 @@ public final boolean equals(Object o) { if (!(o instanceof RichTooltip that)) return false; return showUpTimer == that.showUpTimer && autoUpdate == that.autoUpdate && - titleMargin == that.titleMargin && appliedMargin == that.appliedMargin - && x == that.x && y == that.y && maxWidth == that.maxWidth && + titleMargin == that.titleMargin && appliedMargin == that.appliedMargin && x == that.x && y == that.y && + maxWidth == that.maxWidth && text.equals(that.text) && Objects.equals(parent, that.parent) && pos == that.pos && Objects.equals(tooltipBuilder, that.tooltipBuilder); } diff --git a/src/main/java/brachy/modularui/screen/UISettings.java b/src/main/java/brachy/modularui/screen/UISettings.java index e99db93c..511666ad 100644 --- a/src/main/java/brachy/modularui/screen/UISettings.java +++ b/src/main/java/brachy/modularui/screen/UISettings.java @@ -31,8 +31,10 @@ public class UISettings { @OnlyIn(Dist.CLIENT) private GuiCreator guiSupplier; private Predicate canInteractWith; - @Getter private String theme; - @Getter private final RecipeViewerSettings recipeViewerSettings; + @Getter + private String theme; + @Getter + private final RecipeViewerSettings recipeViewerSettings; @Getter @Setter @Accessors(fluent = true) diff --git a/src/main/java/brachy/modularui/screen/event/OpenScreenEvent.java b/src/main/java/brachy/modularui/screen/event/OpenScreenEvent.java index fe8ffd7a..75ba65af 100644 --- a/src/main/java/brachy/modularui/screen/event/OpenScreenEvent.java +++ b/src/main/java/brachy/modularui/screen/event/OpenScreenEvent.java @@ -14,8 +14,10 @@ public class OpenScreenEvent extends Event { - @Getter private final Screen screen; - @Getter private final List overlays = new ArrayList<>(); + @Getter + private final Screen screen; + @Getter + private final List overlays = new ArrayList<>(); public OpenScreenEvent(Screen screen) { this.screen = screen; diff --git a/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java b/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java index 71ab7f5c..5e77a380 100755 --- a/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java +++ b/src/main/java/brachy/modularui/screen/event/RichTooltipEvent.java @@ -31,13 +31,20 @@ private RichTooltipEvent() {} */ public static class Gather extends Event implements ICancellableEvent { - @Getter private final IRichTextBuilder tooltip; - @Getter protected final ItemStack itemStack; - @Getter protected final GuiContext guiContext; - @Getter protected int x; - @Getter protected int y; - @Getter protected int screenWidth; - @Getter protected int screenHeight; + @Getter + private final IRichTextBuilder tooltip; + @Getter + protected final ItemStack itemStack; + @Getter + protected final GuiContext guiContext; + @Getter + protected int x; + @Getter + protected int y; + @Getter + protected int screenWidth; + @Getter + protected int screenHeight; @Getter @Setter protected int maxWidth; diff --git a/src/main/java/brachy/modularui/screen/viewport/GuiContext.java b/src/main/java/brachy/modularui/screen/viewport/GuiContext.java index 1d05581b..1be76ae9 100644 --- a/src/main/java/brachy/modularui/screen/viewport/GuiContext.java +++ b/src/main/java/brachy/modularui/screen/viewport/GuiContext.java @@ -12,10 +12,10 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; -import com.mojang.blaze3d.vertex.PoseStack; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.blaze3d.vertex.PoseStack; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.ApiStatus; @@ -49,21 +49,32 @@ public static GuiContext getDefault() { /* Mouse states */ private int mouseX; private int mouseY; - @Getter private int lastMouseButton; - @Getter private boolean lastButtonPress; // button pressed = true, button released = false - @Getter private double lastMouseScrollDeltaX, lastMouseScrollDeltaY; + @Getter + private int lastMouseButton; + @Getter + private boolean lastButtonPress; // button pressed = true, button released = false + @Getter + private double lastMouseScrollDeltaX, lastMouseScrollDeltaY; /* Keyboard states */ - @Getter private int lastKeyCode; - @Getter private int lastScanCode; - @Getter private int lastKeyModifiers; - @Getter private char lastCodePoint; - @Getter private boolean lastKeyPress; // key pressed = true, key released = false + @Getter + private int lastKeyCode; + @Getter + private int lastScanCode; + @Getter + private int lastKeyModifiers; + @Getter + private char lastCodePoint; + @Getter + private boolean lastKeyPress; // key pressed = true, key released = false /* Render states */ - @Getter private float renderPartialTicks; - @Getter private long tick = 0; - @Getter private int currentDrawingZ = 0; + @Getter + private float renderPartialTicks; + @Getter + private long tick = 0; + @Getter + private int currentDrawingZ = 0; public GuiContext(UIType uiType) { this.uiType = uiType; diff --git a/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java b/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java index fc5573a8..1fba2a7d 100755 --- a/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java +++ b/src/main/java/brachy/modularui/screen/viewport/GuiViewportStack.java @@ -5,7 +5,6 @@ import brachy.modularui.widget.sizer.Area; import com.mojang.blaze3d.vertex.PoseStack; - import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; @@ -92,7 +91,9 @@ public void popViewport(IViewport viewport) { } else { name = this.top.isViewportMatrix() ? asString(this.top.getViewport()) : "not a viewport"; } - throw new IllegalStateException("Viewports must be popped in reverse order they were pushed. Tried to pop '" + asString(viewport) + "', but last pushed is '" + name + "'."); + throw new IllegalStateException( + "Viewports must be popped in reverse order they were pushed. Tried to pop '" + asString(viewport) + + "', but last pushed is '" + name + "'."); } pop(); updateViewport(true); @@ -112,7 +113,8 @@ public void popMatrix() { } public void push(TransformationMatrix transformationMatrix) { - this.viewportStack.push(newMatrix().construct(transformationMatrix, this.top == null ? null : this.top.getMatrix())); + this.viewportStack + .push(newMatrix().construct(transformationMatrix, this.top == null ? null : this.top.getMatrix())); updateViewport(false); if (this.top.isViewportMatrix()) { this.topViewport = this.top; diff --git a/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java b/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java index af88fdce..20a7cdd6 100755 --- a/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java +++ b/src/main/java/brachy/modularui/screen/viewport/LocatedWidget.java @@ -73,6 +73,5 @@ public boolean equals(LocatedWidget a, LocatedWidget b) { if (a == null || b == null) return false; return Objects.equals(a.getElement(), b.getElement()); } - } } diff --git a/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java b/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java index 837cd292..a9e2842b 100644 --- a/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java +++ b/src/main/java/brachy/modularui/screen/viewport/ModularGuiContext.java @@ -9,11 +9,11 @@ import brachy.modularui.api.widget.IVanillaSlot; import brachy.modularui.api.widget.IWidget; import brachy.modularui.api.widget.ResizeDragArea; -import brachy.modularui.utils.CursorHandler; import brachy.modularui.screen.DraggablePanelWrapper; import brachy.modularui.screen.ModularPanel; import brachy.modularui.screen.ModularScreen; import brachy.modularui.screen.UISettings; +import brachy.modularui.utils.CursorHandler; import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; diff --git a/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java b/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java index f3d2a4a0..10b004f2 100755 --- a/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java +++ b/src/main/java/brachy/modularui/screen/viewport/TransformationMatrix.java @@ -65,7 +65,8 @@ TransformationMatrix construct(IViewport viewport, Area area, @Nullable Matrix4f return construct(viewport, area, parent, true); } - private TransformationMatrix construct(IViewport viewport, Area area, @Nullable Matrix4f parent, boolean isViewport) { + private TransformationMatrix construct(IViewport viewport, Area area, @Nullable Matrix4f parent, + boolean isViewport) { checkInUse(); this.wrapped = null; this.viewport = viewport; diff --git a/src/main/java/brachy/modularui/test/TestBlock.java b/src/main/java/brachy/modularui/test/TestBlock.java index c35af185..e7cc85cb 100644 --- a/src/main/java/brachy/modularui/test/TestBlock.java +++ b/src/main/java/brachy/modularui/test/TestBlock.java @@ -2,22 +2,18 @@ import brachy.modularui.factory.UIFactories; -import com.mojang.serialization.Codec; -import com.mojang.serialization.MapCodec; import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; +import com.mojang.serialization.MapCodec; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -38,7 +34,8 @@ public TestBlock(BiFunction blockEntityCreato } @Override - protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, + BlockHitResult hitResult) { if (!level.isClientSide) { UIFactories.blockEntity().open(player, pos); } @@ -46,7 +43,9 @@ protected InteractionResult useWithoutItem(BlockState state, Level level, BlockP } @Override - public @Nullable BlockEntityTicker getTicker(@NotNull Level level, @NotNull BlockState state, @NotNull BlockEntityType blockEntityType) { + public @Nullable < + T extends BlockEntity> BlockEntityTicker getTicker(@NotNull Level level, @NotNull BlockState state, + @NotNull BlockEntityType blockEntityType) { return (level1, pos, state1, blockEntity) -> ((AbstractBlockEntity) blockEntity).update(); } diff --git a/src/main/java/brachy/modularui/test/TestBlockEntity.java b/src/main/java/brachy/modularui/test/TestBlockEntity.java index bae4fe3e..385400de 100644 --- a/src/main/java/brachy/modularui/test/TestBlockEntity.java +++ b/src/main/java/brachy/modularui/test/TestBlockEntity.java @@ -48,8 +48,6 @@ import brachy.modularui.widgets.slot.PhantomItemSlot; import brachy.modularui.widgets.slot.SlotGroup; -import io.netty.buffer.ByteBuf; - import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; @@ -60,13 +58,13 @@ import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.neoforge.items.ItemStackHandler; +import io.netty.buffer.ByteBuf; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import net.neoforged.neoforge.items.ItemStackHandler; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -74,19 +72,23 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * Various test and demos for synced widgets, slots and JEI interactions. Anything that doesn't fall into any of those categories goes into + * Various test and demos for synced widgets, slots and JEI interactions. Anything that doesn't fall into any of those + * categories goes into * {@link TestGuis}. */ public class TestBlockEntity extends AbstractBlockEntity implements IUIHolder { - private static final Object2IntMap handlerSizeMap = new Object2IntOpenHashMap<>() {{ - put(Items.DIAMOND, 9); - put(Items.EMERALD, 9); - put(Items.GOLD_INGOT, 7); - put(Items.IRON_INGOT, 6); - put(Items.CLAY_BALL, 2); - defaultReturnValue(3); - }}; + private static final Object2IntMap handlerSizeMap = new Object2IntOpenHashMap<>() { + + { + put(Items.DIAMOND, 9); + put(Items.EMERALD, 9); + put(Items.GOLD_INGOT, 7); + put(Items.IRON_INGOT, 6); + put(Items.CLAY_BALL, 2); + defaultReturnValue(3); + } + }; private long time = 0; private final int duration = 80; @@ -97,6 +99,7 @@ public class TestBlockEntity extends AbstractBlockEntity implements IUIHolder mainPanel) { @Override public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, UISettings settings) { - //settings.customContainer(() -> new CraftingModularContainer(3, 3, this.craftingInventory)); - //settings.customGui(() -> TestGuiContainer::new); + // settings.customContainer(() -> new CraftingModularContainer(3, 3, this.craftingInventory)); + // settings.customGui(() -> TestGuiContainer::new); syncManager.registerSlotGroup("item_inv", 3); - syncManager.registerSlotGroup(new SlotGroup("crafting", 3, SlotGroup.STORAGE_SLOT_PRIO * 2).setAllowSorting(false)); + syncManager.registerSlotGroup( + new SlotGroup("crafting", 3, SlotGroup.STORAGE_SLOT_PRIO * 2).setAllowSorting(false)); IntSyncValue cycleStateValue = new IntSyncValue(() -> this.cycleState, val -> this.cycleState = val).allowC2S(); syncManager.getHyperVisor().syncValue("cycle_state", cycleStateValue); syncManager.syncValue("progress", new DoubleSyncValue(() -> (double) this.progress / this.duration)); syncManager.syncValue("display_item", GenericSyncValue.forItem(() -> this.displayItem, null)); - GenericListSyncHandler numberListSyncHandler = GenericListSyncHandler.builder() + GenericListSyncHandler numberListSyncHandler = GenericListSyncHandler + .builder() .getter(() -> this.serverInts) .setter(v -> this.serverInts = v) .serializer(VarInt::write) @@ -145,19 +149,22 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, ItemStack itemStack = ItemStack.OPTIONAL_STREAM_CODEC.decode(packet); if (itemStack.isEmpty()) return new EmptyWidget(); Item item = itemStack.getItem(); - ItemStackHandler handler = stackHandlerMap.computeIfAbsent(item, k -> new ItemStackHandler(handlerSizeMap.getInt(k))); + ItemStackHandler handler = stackHandlerMap.computeIfAbsent(item, + k -> new ItemStackHandler(handlerSizeMap.getInt(k))); String name = BuiltInRegistries.ITEM.getKey(item).toString(); Flow flow = Flow.row(); for (int i = 0; i < handler.getSlots(); i++) { int finalI = i; flow.child(new ItemSlot() - .syncHandler(syncManager1.getOrCreateSyncHandler(name, i, ItemSlotSyncHandler.class, () -> new ItemSlotSyncHandler(new ModularSlot(handler, finalI))))); + .syncHandler(syncManager1.getOrCreateSyncHandler(name, i, ItemSlotSyncHandler.class, + () -> new ItemSlotSyncHandler(new ModularSlot(handler, finalI))))); } return flow; }); - DynamicLinkedSyncHandler> dynamicLinkedSyncHandler = new DynamicLinkedSyncHandler<>(numberListSyncHandler) + DynamicLinkedSyncHandler> dynamicLinkedSyncHandler = new DynamicLinkedSyncHandler<>( + numberListSyncHandler) .widgetProvider((syncManager1, value1) -> { List vals = value1.getValue(); return Flow.row() @@ -210,7 +217,8 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .key('O', new ItemSlot().slot(new ModularCraftingSlot(this.craftingInventory, 9) .inputInventory(this.craftingInventory) .gridSize(3, 3))) - .key('D', new ItemDisplayWidget().syncHandler("display_item").displayAmount(true)) + .key('D', + new ItemDisplayWidget().syncHandler("display_item").displayAmount(true)) .slotGroup("crafting") .build() .margin(5, 5, 20, 5) @@ -234,10 +242,13 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .name("buttons_and_values_col") .widthRel(0.5f) .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) - .child(Text.str("Storage slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Storage slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("III", "III") - .key('I', i -> new ItemSlot().slot(new ModularSlot(this.storage, i))) + .key('I', + i -> new ItemSlot() + .slot(new ModularSlot(this.storage, i))) .slotGroup("item_inv") .build() .placeSortButtonsTopRightVertical()) @@ -247,14 +258,20 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .tooltip(tooltip -> { tooltip.showUpTimer(10); tooltip.addLine(Text.str("Test Line g")); - tooltip.addLine(Text.str("An image inside of a tooltip:")); - tooltip.addDrawableLine(GuiTextures.MUI_LOGO.asIcon().size(50).alignment(Alignment.TopCenter)); + tooltip.addLine( + Text.str("An image inside of a tooltip:")); + tooltip.addDrawableLine( + GuiTextures.MUI_LOGO.asIcon().size(50) + .alignment(Alignment.TopCenter)); tooltip.addLine(Text.str("And here a circle:")); tooltip.addDrawableLine(new Circle() - .color(Color.RED.darker(2), Color.RED.brighter(2)) - .asIcon() - .size(20)) - .addDrawableLine(new ItemDrawable(new ItemStack(Items.DIAMOND)).asIcon()) + .color(Color.RED.darker(2), + Color.RED.brighter(2)) + .asIcon() + .size(20)) + .addDrawableLine(new ItemDrawable( + new ItemStack(Items.DIAMOND)) + .asIcon()) .pos(RichTooltip.Pos.LEFT); }) .onMousePressed((context, mouseButton) -> { @@ -268,77 +285,101 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager syncManager, .reverseLayout(false) .child(new ToggleButton() .valueWrapped(cycleStateValue, 0) - .overlay(GuiTextures.CYCLE_BUTTON_DEMO.getSubArea(0, 0, 1, 1 / 3f))) + .overlay(GuiTextures.CYCLE_BUTTON_DEMO + .getSubArea(0, 0, 1, 1 / 3f))) .child(new ToggleButton() .valueWrapped(cycleStateValue, 1) - .overlay(GuiTextures.CYCLE_BUTTON_DEMO.getSubArea(0, 1 / 3f, 1, 2 / 3f))) + .overlay(GuiTextures.CYCLE_BUTTON_DEMO + .getSubArea(0, 1 / 3f, 1, 2 / 3f))) .child(new ToggleButton() .valueWrapped(cycleStateValue, 2) - .overlay(GuiTextures.CYCLE_BUTTON_DEMO.getSubArea(0, 2 / 3f, 1, 1)))) + .overlay(GuiTextures.CYCLE_BUTTON_DEMO + .getSubArea(0, 2 / 3f, 1, 1)))) .child(Flow.row() .name("progress_row") .coverChildrenHeight() .mainAxisAlignment(Alignment.MainAxis.SPACE_AROUND) .child(new ProgressWidget() .syncHandler("progress") - .texture(GuiTextures.PROGRESS_ARROW, ProgressDrawable.Direction.RIGHT) + .texture(GuiTextures.PROGRESS_ARROW, + ProgressDrawable.Direction.RIGHT) .size(20)) .child(CompositeProgress.circularLike4Slice( - GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0f, 1, 0.5f), - GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0.5f, 1, 1f), - CircularProgressDrawable.Direction.CW) + GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0f, 1, + 0.5f), + GuiTextures.PROGRESS_CYCLE.getSubArea(0, 0.5f, + 1, 1f), + CircularProgressDrawable.Direction.CW) .asWidget() .syncHandler("progress") - .size(20))) - ) + .size(20)))) .child(Flow.col() .name("slots_col") .widthRel(0.5f) .heightRelOffset(1f, -6) // space for player sort buttons .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) - .child(Text.str("Oversized slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Oversized slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("III") - .key('I', i -> new ItemSlot().slot(new ModularSlot(this.oversizedStorage, i).ignoreMaxStackSize(true))) + .key('I', i -> new ItemSlot() + .slot(new ModularSlot(this.oversizedStorage, i) + .ignoreMaxStackSize(true))) .build()) - .child(Text.str("Phantom slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Phantom slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("III") - .key('I', i -> new PhantomItemSlot().slot(new ModularSlot(this.phantomStorage, i).ignoreMaxStackSize(true))) + .key('I', + i -> new PhantomItemSlot().slot( + new ModularSlot(this.phantomStorage, i) + .ignoreMaxStackSize(true))) .build()) - .child(Text.str("Fluid slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Fluid slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("FFF") - .key('F', i -> new FluidSlot().syncHandler(new FluidSlotSyncHandler(this.fluidStorage, i))) + .key('F', i -> new FluidSlot().syncHandler( + new FluidSlotSyncHandler(this.fluidStorage, i))) .build()) - .child(Text.str("Phantom Fluid slots").asWidget().scale(0.7f).padding(1)) + .child(Text.str("Phantom Fluid slots").asWidget().scale(0.7f) + .padding(1)) .child(SlotGroupWidget.builder() .matrix("FFF") - .key('F', i -> new FluidSlot().syncHandler(new FluidSlotSyncHandler(this.phantomFluidStorage, i).phantom(true))) - .build()) - ))) + .key('F', + i -> new FluidSlot() + .syncHandler(new FluidSlotSyncHandler( + this.phantomFluidStorage, i) + .phantom(true))) + .build())))) .addPage(new ParentWidget<>() .name("dynamic_sync_page") .sizeRel(1f) .child(Flow.col() .name("dynamic widgets") - .child(Text.str("Dynamic synced widget demo. Items act as keys to a unique storage with different amount of slots.").asWidget().scale(0.7f)) + .child(Text.str( + "Dynamic synced widget demo. Items act as keys to a unique storage with different amount of slots.") + .asWidget().scale(0.7f)) .child(new ItemSlot() .slot(new ModularSlot(this.storageInventory0, 0) .changeListener(((oldItem, newItem, client, init) -> { - if (client && !ItemStack.isSameItemSameComponents(oldItem, newItem)) { - dynamicSyncHandler.notifyUpdate(packet -> ItemStack.OPTIONAL_STREAM_CODEC.encode(packet, newItem)); + if (client && + !ItemStack.isSameItemSameComponents(oldItem, + newItem)) { + dynamicSyncHandler.notifyUpdate( + packet -> ItemStack.OPTIONAL_STREAM_CODEC + .encode(packet, newItem)); } })))) .child(new DynamicWidget<>() .widthRel(1f) .syncHandler(dynamicSyncHandler)) - .child(Text.str("Dynamic linked sync handler demo.").asWidget().scale(0.7f).marginTop(6)) + .child(Text.str("Dynamic linked sync handler demo.").asWidget() + .scale(0.7f).marginTop(6)) .child(new DynamicWidget<>() .widthRel(1f) .coverChildrenHeight() - .syncHandler(dynamicLinkedSyncHandler)) - ))) + .syncHandler(dynamicLinkedSyncHandler))))) .child(SlotGroupWidget.playerInventory(false))); return panel; } @@ -355,8 +396,8 @@ public ModularPanel openSecondWindow(PanelSyncManager syncManager, IPanelHand syncManager.registerSlotGroup(slotGroup); AtomicInteger number = new AtomicInteger(0); syncManager.syncValue("int_value", new IntSyncValue(number::get, number::set)); - IPanelHandler panelSyncHandler = syncManager.syncedPanel("other_panel_2", true, (syncManager1, syncHandler1) -> - openThirdWindow(syncManager1, syncHandler1, number)); + IPanelHandler panelSyncHandler = syncManager.syncedPanel("other_panel_2", true, + (syncManager1, syncHandler1) -> openThirdWindow(syncManager1, syncHandler1, number)); IntSyncValue num = syncManager.getHyperVisor().findSyncHandler("cycle_state", IntSyncValue.class); panel.child(ButtonWidget.panelCloseButton()) .child(new ButtonWidget<>() @@ -386,7 +427,8 @@ public ModularPanel openSecondWindow(PanelSyncManager syncManager, IPanelHand return panel; } - public ModularPanel openThirdWindow(PanelSyncManager syncManager, IPanelHandler syncHandler, AtomicInteger integer) { + public ModularPanel openThirdWindow(PanelSyncManager syncManager, IPanelHandler syncHandler, + AtomicInteger integer) { ModularPanel panel = new ModularPanel<>("third_window") .disablePanelsBelow(false) .closeOnOutOfBoundsClick(false) diff --git a/src/main/java/brachy/modularui/test/TestGuis.java b/src/main/java/brachy/modularui/test/TestGuis.java index 31377fc0..383303c0 100644 --- a/src/main/java/brachy/modularui/test/TestGuis.java +++ b/src/main/java/brachy/modularui/test/TestGuis.java @@ -1,6 +1,5 @@ package brachy.modularui.test; -import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.ModularUI; import brachy.modularui.animation.Animator; import brachy.modularui.animation.IAnimator; @@ -11,7 +10,6 @@ import brachy.modularui.api.drawable.Text; import brachy.modularui.api.layout.IViewportStack; import brachy.modularui.api.widget.IWidget; -import brachy.modularui.drawable.schema.BlockHighlight; import brachy.modularui.drawable.FluidDrawable; import brachy.modularui.drawable.GuiDraw; import brachy.modularui.drawable.GuiTextures; @@ -21,9 +19,10 @@ import brachy.modularui.drawable.graph.GraphDrawable; import brachy.modularui.drawable.progress.CircularProgressDrawable; import brachy.modularui.drawable.progress.ProgressDrawable; -import brachy.modularui.factory.ClientGUI; import brachy.modularui.drawable.schema.ArraySchema; +import brachy.modularui.drawable.schema.BlockHighlight; import brachy.modularui.drawable.schema.ISchema; +import brachy.modularui.factory.ClientGUI; import brachy.modularui.screen.CustomModularScreen; import brachy.modularui.screen.ModularPanel; import brachy.modularui.screen.ModularScreen; @@ -33,6 +32,7 @@ import brachy.modularui.utils.ColorShade; import brachy.modularui.utils.Interpolation; import brachy.modularui.utils.Interpolations; +import brachy.modularui.utils.MUIRenderTypes; import brachy.modularui.utils.math.DAM; import brachy.modularui.value.BoolValue; import brachy.modularui.value.DoubleValue; @@ -66,9 +66,9 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.material.Fluids; import net.neoforged.neoforge.fluids.FluidStack; -import com.mojang.blaze3d.vertex.VertexConsumer; import com.google.common.base.CaseFormat; +import com.mojang.blaze3d.vertex.VertexConsumer; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import org.apache.commons.lang3.tuple.Pair; @@ -109,8 +109,10 @@ public TestGuis() { } /** - * This method finds all 'build___UI' methods in this class via reflection and adds a button that opens that UI to a list widget. - * This makes it very convenient to add and test test-screens without having to swap out the screen that the diamond item opens. + * This method finds all 'build___UI' methods in this class via reflection and adds a button that opens that UI to a + * list widget. + * This makes it very convenient to add and test test-screens without having to swap out the screen that the diamond + * item opens. */ @Override public @NotNull ModularPanel buildUI(ModularGuiContext context) { @@ -136,14 +138,16 @@ public TestGuis() { String name = m.getName(); if (name.startsWith("build")) name = name.substring(5); if (name.endsWith("UI")) name = name.substring(0, name.length() - 2); - String codeTextureName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name); + String codeTextureName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, + name); name = name.replaceAll("([a-z])([A-Z])", "$1 $2"); return button(name) .onMousePressed((context1, button) -> { try { ModularPanel panel = (ModularPanel) m.invoke(null); if (TestGuis.withCode) { - // WIP: this is meant to put an image of the code next to ui for showcase purpose + // WIP: this is meant to put an image of the code next to ui for + // showcase purpose panel.child(UITexture.builder() .location("gui/code/" + codeTextureName) .build() @@ -151,23 +155,26 @@ public TestGuis() { .leftRel(1f) .heightRel(1f)); } - ClientGUI.open(new ModularScreen(ModularUI.MOD_ID, panel).openParentOnClose(true)); + ClientGUI.open(new ModularScreen(ModularUI.MOD_ID, panel) + .openParentOnClose(true)); } catch (IllegalAccessException | InvocationTargetException e) { ModularUI.LOGGER.throwing(e); } return true; }); }) - /*.child(button("OpenGL test") - .onMousePressed(button -> { - ClientGUI.open(new GLTestGui().openParentOnClose(true)); - return true; - })) - .child(button("Sortable List") - .onMousePressed(button -> { - ClientGUI.open(new TestGui().openParentOnClose(true)); - return true; - }))*/ + /* + * .child(button("OpenGL test") + * .onMousePressed(button -> { + * ClientGUI.open(new GLTestGui().openParentOnClose(true)); + * return true; + * })) + * .child(button("Sortable List") + * .onMousePressed(button -> { + * ClientGUI.open(new TestGui().openParentOnClose(true)); + * return true; + * })) + */ .child(button("Test self") .onMousePressed((context1, button) -> { ClientGUI.open(this); @@ -204,7 +211,6 @@ private static ButtonWidget button(String text) { .margin(1) .name("G:" + i + ",W:" + j); }))); - } public static @NotNull ModularPanel buildPendulumAnimationUI() { @@ -266,53 +272,63 @@ private static ButtonWidget button(String text) { stack.translate(x0, y0); stack.scale(scale, scale); stack.translate(-x0, -y0); - widget.color(Color.lerp(0xFF040404, Color.RED.main, Math.min(1f, 1.2f * logGrowVal))); + widget.color( + Color.lerp(0xFF040404, Color.RED.main, Math.min(1f, 1.2f * logGrowVal))); }))); } - /*public static @NotNull ModularPanel buildSpriteAndEntityUI() { - TextureAtlasSprite sprite = SpriteHelper.getSpriteOfBlockState(GameObjectHelper.getBlockState("minecraft", "command_block"), EnumFacing.UP); - // SpriteHelper.getSpriteOfItem(new ItemStack(Items.DIAMOND)); - Entity entity = FakeEntity.create(EntityDragon.class); - float period = 3000f; - return ModularPanel.defaultPanel("main") - .size(150) - .overlay(new Rectangle() - .color(Color.GREEN.main) - .hollow(2) - .asIcon().margin(5)) - .child(new TextWidget<>(IKey.str("Test String")).scale(0.6f).horizontalCenter().top(7)) - .child(new DraggableWidget<>() - .background(new SpriteDrawable(sprite)) - .size(20) - .alignX(0.5f) - .top(20) - .tooltipBuilder(tooltip -> { - tooltip.addLine( - "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " - + "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. " - + "Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. " - + "Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem"); - tooltip.addLine("Longer Line 2"); - tooltip.addLine("Line 3"); - tooltip.alignment(Alignment.Center); - tooltip.scale(0.5f); - tooltip.pos(RichTooltip.Pos.NEXT_TO_MOUSE); - })) - .child(new IDrawable() { - @Override - public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { - GuiDraw.drawEntity(context.getGraphics(), entity, 0, 0, width, height, context.getCurrentDrawingZ(), (graphics, e) -> { - // TODO the drawable doesnt seem to update the rotation - float scale = 0.9f; - graphics.pose().scale(scale, scale, scale); - graphics.pose().translate(0, 7, 0); - //graphics.pose().rotate(35, 1, 0, 0); - //graphics.pose().rotate(360 * (Util.getMillis() % period) / period, 0, 1, 0); - }, null); - } - }.asWidget().alignX(0.5f).bottom(10).size(100, 75)); - }*/ + /* + * public static @NotNull ModularPanel buildSpriteAndEntityUI() { + * TextureAtlasSprite sprite = SpriteHelper.getSpriteOfBlockState(GameObjectHelper.getBlockState("minecraft", + * "command_block"), EnumFacing.UP); + * // SpriteHelper.getSpriteOfItem(new ItemStack(Items.DIAMOND)); + * Entity entity = FakeEntity.create(EntityDragon.class); + * float period = 3000f; + * return ModularPanel.defaultPanel("main") + * .size(150) + * .overlay(new Rectangle() + * .color(Color.GREEN.main) + * .hollow(2) + * .asIcon().margin(5)) + * .child(new TextWidget<>(IKey.str("Test String")).scale(0.6f).horizontalCenter().top(7)) + * .child(new DraggableWidget<>() + * .background(new SpriteDrawable(sprite)) + * .size(20) + * .alignX(0.5f) + * .top(20) + * .tooltipBuilder(tooltip -> { + * tooltip.addLine( + * "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " + * + + * "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. " + * + + * "Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. " + * + + * "Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem" + * ); + * tooltip.addLine("Longer Line 2"); + * tooltip.addLine("Line 3"); + * tooltip.alignment(Alignment.Center); + * tooltip.scale(0.5f); + * tooltip.pos(RichTooltip.Pos.NEXT_TO_MOUSE); + * })) + * .child(new IDrawable() { + * + * @Override + * public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { + * GuiDraw.drawEntity(context.getGraphics(), entity, 0, 0, width, height, context.getCurrentDrawingZ(), (graphics, + * e) -> { + * // TODO the drawable doesnt seem to update the rotation + * float scale = 0.9f; + * graphics.pose().scale(scale, scale, scale); + * graphics.pose().translate(0, 7, 0); + * //graphics.pose().rotate(35, 1, 0, 0); + * //graphics.pose().rotate(360 * (Util.getMillis() % period) / period, 0, 1, 0); + * }, null); + * } + * }.asWidget().alignX(0.5f).bottom(10).size(100, 75)); + * } + */ public static @NotNull ModularPanel buildRichTextUI() { IntValue integer = new IntValue(0); @@ -325,8 +341,10 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget .addDrawable(new ItemDrawable(new ItemStack(Blocks.GRASS_BLOCK)) .asIcon() .asHoverable() - .tooltip(richTooltip -> richTooltip.addFromItem(new ItemStack(Blocks.GRASS_BLOCK)) - .add(Text.GRAY + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."))) + .tooltip(richTooltip -> richTooltip + .addFromItem(new ItemStack(Blocks.GRASS_BLOCK)) + .add(Text.GRAY + + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."))) .add(", nice to ") .addDrawable(new ItemDrawable(new ItemStack(Items.PORKCHOP)) .asIcon() @@ -346,19 +364,18 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget .newLine() .newLine() .add(Text.comp(Text.comp( - Text.str("Underline all: "), - Text.comp( - Text.str("Green Text, "), - Text.str("this is red").style(Text.RED), - Text.str(" and this should be green again")) - .style(Text.GREEN), - Text.str(". Still underlined, ")) + Text.str("Underline all: "), + Text.comp( + Text.str("Green Text, "), + Text.str("this is red").style(Text.RED), + Text.str(" and this should be green again")) + .style(Text.GREEN), + Text.str(". Still underlined, ")) .style(Text.UNDERLINE), Text.str("but not anymore."))) .newLine() .addDrawable(Text.str("Green, %s, %s and green again", Text.str("red").style(Text.RED), - Text.str("underline").style(null, Text.UNDERLINE) - ).style(Text.GREEN)) + Text.str("underline").style(null, Text.UNDERLINE)).style(Text.GREEN)) .newLine() .add(Text.RESET + "" + Text.UNDERLINE + "Underlined" + Text.RESET) .newLine() @@ -368,37 +385,43 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget int i = integer.getIntValue() + 1; integer.setIntValue(i); return Text.str("key [%s]", Text.str("arg") - .style(Text.UNDERLINE, Text.BLACK)) + .style(Text.UNDERLINE, Text.BLACK)) .style(i % 30 > 5 ? Text.RED : Text.DARK_BLUE); }).fallbackStyle(Text.BOLD), Text.str(" Test"))) - .textShadow(false) - )); + .textShadow(false))); } public static @NotNull ModularPanel buildWorldSchemaUI() { - /*TrackedDummyWorld world = new TrackedDummyWorld(); - world.addBlock(new BlockPos(0, 0, 0), new BlockInfo(Blocks.DIAMOND_BLOCK.getDefaultState())); - world.addBlock(new BlockPos(0, 1, 0), new BlockInfo(Blocks.BEDROCK.getDefaultState())); - world.addBlock(new BlockPos(1, 0, 1), new BlockInfo(Blocks.GOLD_BLOCK.getDefaultState()));*/ -/* return ModularPanel.defaultPanel("main") - .size(150) - .overlay(new SchemaRenderer(BoxSchema.of(Minecraft.getMinecraft().world, new BlockPos(Platform.getClientPlayer()), 5)) - .cameraFunc((camera, schema) -> { - double pitch = Math.PI / 4; - double T = 4000D; - double yaw = Minecraft.getSystemTime() % T / T * Math.PI * 2; - camera.setLookAt(new BlockPos(Platform.getClientPlayer()), 20, yaw, pitch); - }) - .isometric(true) - .asIcon().size(140));*/ - - /*MapSchema world = new MapSchema.Builder() - .add(new BlockPos(0, 0, 0), Blocks.DIAMOND_BLOCK.getDefaultState()) - .add(new BlockPos(0, 1, 0), Blocks.BEDROCK.getDefaultState()) - .add(new BlockPos(0, 2, 0), Blocks.WOOL.getDefaultState()) - .add(new BlockPos(1, 0, 1), Blocks.GOLD_BLOCK.getDefaultState()) - .add(new BlockPos(0, 3, 0), Blocks.BEACON.getDefaultState()) - .build();*/ + /* + * TrackedDummyWorld world = new TrackedDummyWorld(); + * world.addBlock(new BlockPos(0, 0, 0), new BlockInfo(Blocks.DIAMOND_BLOCK.getDefaultState())); + * world.addBlock(new BlockPos(0, 1, 0), new BlockInfo(Blocks.BEDROCK.getDefaultState())); + * world.addBlock(new BlockPos(1, 0, 1), new BlockInfo(Blocks.GOLD_BLOCK.getDefaultState())); + */ + /* + * return ModularPanel.defaultPanel("main") + * .size(150) + * .overlay(new SchemaRenderer(BoxSchema.of(Minecraft.getMinecraft().world, new + * BlockPos(Platform.getClientPlayer()), 5)) + * .cameraFunc((camera, schema) -> { + * double pitch = Math.PI / 4; + * double T = 4000D; + * double yaw = Minecraft.getSystemTime() % T / T * Math.PI * 2; + * camera.setLookAt(new BlockPos(Platform.getClientPlayer()), 20, yaw, pitch); + * }) + * .isometric(true) + * .asIcon().size(140)); + */ + + /* + * MapSchema world = new MapSchema.Builder() + * .add(new BlockPos(0, 0, 0), Blocks.DIAMOND_BLOCK.getDefaultState()) + * .add(new BlockPos(0, 1, 0), Blocks.BEDROCK.getDefaultState()) + * .add(new BlockPos(0, 2, 0), Blocks.WOOL.getDefaultState()) + * .add(new BlockPos(1, 0, 1), Blocks.GOLD_BLOCK.getDefaultState()) + * .add(new BlockPos(0, 3, 0), Blocks.BEACON.getDefaultState()) + * .build(); + */ ISchema schema = ArraySchema.builder() .layer("D D", " ", " ", " ") @@ -419,7 +442,7 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget var panel = ModularPanel.defaultPanel("main").size(170); panel.child(new SchemaWidget(renderer) - .full()) + .full()) .child(new SchemaWidget.LayerButton(renderer, 0, 3) .bottom(1) .left(1) @@ -469,7 +492,8 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { .marginBottom(-1) .widgetThemeKey(IThemeApi.BUTTON) .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) - .setEnabledIf(w -> text.toLowerCase().contains(searchValue.getStringValue())) + .setEnabledIf( + w -> text.toLowerCase().contains(searchValue.getStringValue())) .child(new ItemDrawable(stack).asWidget()) .child(new ScrollingTextWidget(Text.str(text)) .widgetThemeKey(IThemeApi.BUTTON) @@ -501,7 +525,8 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { Rectangle color1 = new Rectangle().color(Color.BLACK.main); Rectangle color2 = new Rectangle().color(Color.WHITE.main); - IDrawable gradient = (context1, x, y, width, height, widgetTheme) -> GuiDraw.drawHorizontalGradientRect(context1.getGraphics(), x, y, width, height, color1.getColor(), color2.getColor()); + IDrawable gradient = (context1, x, y, width, height, widgetTheme) -> GuiDraw.drawHorizontalGradientRect( + context1.getGraphics(), x, y, width, height, color1.getColor(), color2.getColor()); IDrawable correctedGradient = (context1, x, y, width, height, widgetTheme) -> { int points = 500; Matrix4f pose = context1.graphicsPose().last().pose(); @@ -520,18 +545,22 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { ModularPanel panel = new ModularPanel<>("colors").width(300).coverChildrenHeight().padding(7); - IPanelHandler colorPicker1 = IPanelHandler.simple(panel, (mainPanel, player) -> new ColorPickerDialog("color_picker1", color1.getColor(), true) - .resultConsumer(color1::color) - .draggable(true) - .relative(panel) - .top(0) - .rightRel(1f), true); - IPanelHandler colorPicker2 = IPanelHandler.simple(panel, (mainPanel, player) -> new ColorPickerDialog("color_picker2", color2.getColor(), true) - .resultConsumer(color2::color) - .draggable(true) - .relative(panel) - .top(0) - .leftRel(1f), true); + IPanelHandler colorPicker1 = IPanelHandler.simple(panel, + (mainPanel, player) -> new ColorPickerDialog("color_picker1", color1.getColor(), true) + .resultConsumer(color1::color) + .draggable(true) + .relative(panel) + .top(0) + .rightRel(1f), + true); + IPanelHandler colorPicker2 = IPanelHandler.simple(panel, + (mainPanel, player) -> new ColorPickerDialog("color_picker2", color2.getColor(), true) + .resultConsumer(color2::color) + .draggable(true) + .relative(panel) + .top(0) + .leftRel(1f), + true); return panel .child(Flow.column() @@ -576,7 +605,8 @@ public static ModularPanel buildCollapseDisabledChildrenUI() { public static ModularPanel buildContextMenu() { List options1 = IntStream.range(0, 5).mapToObj(i -> "Option " + (i + 1)).collect(Collectors.toList()); - List options2 = IntStream.range(0, 5).mapToObj(i -> "Sub Option " + (i + 1)).collect(Collectors.toList()); + List options2 = IntStream.range(0, 5).mapToObj(i -> "Sub Option " + (i + 1)) + .collect(Collectors.toList()); ObjectValue itemValue = new ObjectValue<>(ItemStack.class, new ItemStack(Items.ACACIA_DOOR)); return new ModularPanel<>("context_menu_test") .size(150) @@ -595,7 +625,7 @@ public static ModularPanel buildContextMenu() { .overlay(Text.str("Sub Menu")) .openRightDown() .menuList(l1 -> l1 - //.width(90) + // .width(90) .maxSize(80) .children(options2, s -> Text.str(s).asWidget()))))) .child(new DropdownWidget<>("test_dropdown", ItemStack.class) @@ -617,8 +647,7 @@ public static ModularPanel buildContextMenu() { .child(new ItemDrawable(item).asWidget()) .child(Text.str(item.getDisplayName().getString()).asWidget() .widgetThemeKey(IThemeApi.BUTTON) - .invisible())) - ); + .invisible()))); } public static @NotNull ModularPanel buildGraphUI() { @@ -806,15 +835,14 @@ private static Rectangle rndRect(IntList colors, Random random) { .filledTexture(new FluidDrawable(new FluidStack(Fluids.WATER, 1))) .counterClockwise() .asWidget())) - .coverChildren() - ); + .coverChildren()); } private static class TestPanel extends ModularPanel { public TestPanel(String name) { super(name); - //background(GuiTextures.BACKGROUND); + // background(GuiTextures.BACKGROUND); size(100, 100); } diff --git a/src/main/java/brachy/modularui/test/TestHandler.java b/src/main/java/brachy/modularui/test/TestHandler.java index b416cf68..875b1ea6 100644 --- a/src/main/java/brachy/modularui/test/TestHandler.java +++ b/src/main/java/brachy/modularui/test/TestHandler.java @@ -17,7 +17,6 @@ import brachy.modularui.screen.event.RichTooltipEvent; import brachy.modularui.screen.viewport.GuiContext; import brachy.modularui.screen.viewport.ModularGuiContext; -import brachy.modularui.theme.ReloadThemeEvent; import brachy.modularui.theme.SelectableTheme; import brachy.modularui.theme.ThemeBuilder; import brachy.modularui.theme.WidgetTheme; @@ -31,7 +30,6 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import com.mojang.datafixers.util.Either; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.bus.api.SubscribeEvent; @@ -39,6 +37,7 @@ import net.neoforged.neoforge.client.event.RenderTooltipEvent; import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import com.mojang.datafixers.util.Either; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -58,11 +57,11 @@ public class TestHandler { .widgetThemeHover(IThemeApi.TOGGLE_BUTTON, new SelectableTheme.Builder<>() .selectedIconColor(Color.DEEP_PURPLE.brighter(0)) .selectedBackground("slot_fluid") - .background("slot_item") - ) + .background("slot_item")) .textColor(IThemeApi.TEXT_FIELD, Color.DEEP_PURPLE.main); private static final IIcon tooltipLine = new IDrawable() { + @Override public void draw(GuiContext context, int x, int y, int width, int height, WidgetTheme widgetTheme) { int high = Color.PURPLE.main; @@ -76,7 +75,6 @@ public void draw(GuiContext context, int x, int y, int width, int height, Widget private static final RandomSource random = RandomSource.createThreadSafe(); public static ItemStack getRandomItem() { - if (allItems == null) { allItems = new ArrayList<>(); for (Item item : BuiltInRegistries.ITEM) { @@ -136,9 +134,11 @@ public static void onPreInit() { @SubscribeEvent public static void onOpenScreen(OpenScreenEvent event) { if (ModularUIConfig.enableTestOverlays()) { - /*if (event.getScreen() instanceof gui) { - event.addOverlay(getMainMenuOverlayTest(gui)); - } else */ + /* + * if (event.getScreen() instanceof gui) { + * event.addOverlay(getMainMenuOverlayTest(gui)); + * } else + */ if (event.getScreen() instanceof AbstractContainerScreen gui) { event.addOverlay(getContainerOverlayTest(gui)); } @@ -149,33 +149,37 @@ public static void onOpenScreen(OpenScreenEvent event) { @SubscribeEvent public static void onBuildPanel(BuildPanelEvent.MainPanel event) { if (event.matches(ModularUI.MOD_ID, "test_tile")) { - Flow flow = WidgetTree.findChildAt(event.getOpeningPanel(), Flow.class, "main_col", "paged", "dynamic_sync_page", "dynamic widgets"); + Flow flow = WidgetTree.findChildAt(event.getOpeningPanel(), Flow.class, "main_col", "paged", + "dynamic_sync_page", "dynamic widgets"); flow.addChild(Text.str("Added from Event").asWidget(), 0); } } - /*private ModularScreen getMainMenuOverlayTest(GuiMainMenu gui) { - TextWidget title = new TextWidget<>(IKey.str("ModularUI")); - int[] colors = {Color.WHITE.main, Color.AMBER.main, Color.BLUE.main, Color.GREEN.main, Color.DEEP_PURPLE.main, Color.RED.main}; - AtomicInteger k = new AtomicInteger(); - return new ModularScreen(ModularUI.ID, - ModularPanel.defaultPanel("overlay") - .fullScreenInvisible() - .child(title.scale(5f) - .shadow(true) - .color(colors[k.get()]) - .leftRel(0.5f).topRel(0.07f)) - .child(new ButtonWidget<>() // test button overlapping - .topRel(0.25f, 59, 0f) - .leftRelOffset(0.5f, 91) - .size(44) - .overlay(IKey.str("Fun Button")) - .onMousePressed(mouseButton -> { - k.set((k.get() + 1) % colors.length); - title.color(colors[k.get()]); - return true; - }))); - }*/ + /* + * private ModularScreen getMainMenuOverlayTest(GuiMainMenu gui) { + * TextWidget title = new TextWidget<>(IKey.str("ModularUI")); + * int[] colors = {Color.WHITE.main, Color.AMBER.main, Color.BLUE.main, Color.GREEN.main, Color.DEEP_PURPLE.main, + * Color.RED.main}; + * AtomicInteger k = new AtomicInteger(); + * return new ModularScreen(ModularUI.ID, + * ModularPanel.defaultPanel("overlay") + * .fullScreenInvisible() + * .child(title.scale(5f) + * .shadow(true) + * .color(colors[k.get()]) + * .leftRel(0.5f).topRel(0.07f)) + * .child(new ButtonWidget<>() // test button overlapping + * .topRel(0.25f, 59, 0f) + * .leftRelOffset(0.5f, 91) + * .size(44) + * .overlay(IKey.str("Fun Button")) + * .onMousePressed(mouseButton -> { + * k.set((k.get() + 1) % colors.length); + * title.color(colors[k.get()]); + * return true; + * }))); + * } + */ @OnlyIn(Dist.CLIENT) private static ModularScreen getContainerOverlayTest(AbstractContainerScreen gui) { diff --git a/src/main/java/brachy/modularui/test/TestItem.java b/src/main/java/brachy/modularui/test/TestItem.java index cdf913c2..228319eb 100644 --- a/src/main/java/brachy/modularui/test/TestItem.java +++ b/src/main/java/brachy/modularui/test/TestItem.java @@ -38,20 +38,20 @@ public ModularPanel buildUI(PlayerInventoryGuiData data, PanelSyncManager syncManager.registerSlotGroup("mixer_items", 2); ModularPanel panel = ModularPanel.defaultPanel("knapping_gui").resizeableOnDrag(true); panel.child(Flow.col().margin(7) - .child(new ParentWidget<>().widthRel(1f).expanded() - .child(SlotGroupWidget.builder() - .row("I I") - .row(" I") - .row(" ") - .row(" I ") - .key('I', index -> new ItemSlot().slot(SyncHandlers.itemSlot(ihm, index) - .ignoreMaxStackSize(true) - .slotGroup("mixer_items") - // do not allow putting items which can hold other items into the item - // some mods don't do this on their backpacks, so it won't catch those cases - .filter(stack -> stack.getCapability(Capabilities.ItemHandler.ITEM) == null))) - .build())) - .child(SlotGroupWidget.playerInventory(false))) + .child(new ParentWidget<>().widthRel(1f).expanded() + .child(SlotGroupWidget.builder() + .row("I I") + .row(" I") + .row(" ") + .row(" I ") + .key('I', index -> new ItemSlot().slot(SyncHandlers.itemSlot(ihm, index) + .ignoreMaxStackSize(true) + .slotGroup("mixer_items") + // do not allow putting items which can hold other items into the item + // some mods don't do this on their backpacks, so it won't catch those cases + .filter(stack -> stack.getCapability(Capabilities.ItemHandler.ITEM) == null))) + .build())) + .child(SlotGroupWidget.playerInventory(false))) .child(GuiTextures.ANIMATED_TEXTURE_TEST.asWidget().size(32).leftRel(1f).topRel(0f).margin(7)); return panel; diff --git a/src/main/java/brachy/modularui/test/TestMachine.java b/src/main/java/brachy/modularui/test/TestMachine.java index d93151b2..a1897b33 100644 --- a/src/main/java/brachy/modularui/test/TestMachine.java +++ b/src/main/java/brachy/modularui/test/TestMachine.java @@ -56,7 +56,6 @@ import net.neoforged.neoforge.items.ItemHandlerHelper; import net.neoforged.neoforge.items.ItemStackHandler; import net.neoforged.neoforge.items.wrapper.CombinedInvWrapper; -import net.neoforged.neoforge.items.wrapper.EmptyItemHandler; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -82,7 +81,8 @@ public static class BE extends AbstractBlockEntity implements IUIHolder buildUI(PosGuiData data, PanelSyncManager syncManager, UI .coverChildren(176, 30) .padding(7) .widgetThemeKey(IThemeApi.PANEL) - .child(Recipes.buildMachineUI(panel, this.inputItems, this.outputItems, this.inputFluids, this.outputFluids, new DoubleSyncValue(this::getProgress), false)) + .child(Recipes.buildMachineUI(panel, this.inputItems, this.outputItems, + this.inputFluids, this.outputFluids, new DoubleSyncValue(this::getProgress), + false)) .child(new ParentWidget<>() .coverChildren() .decoration() @@ -133,11 +135,11 @@ public ModularPanel buildUI(PosGuiData data, PanelSyncManager syncManager, UI .bottom(7) .rightRelAnchor(0, 1f) .child(new ToggleButton() - .value(new BooleanSyncValue(() -> this.paused, v -> this.paused = v).allowC2S()) + .value(new BooleanSyncValue(() -> this.paused, v -> this.paused = v) + .allowC2S()) .overlay(true, GuiTextures.PLAY) .overlay(false, GuiTextures.PAUSE)) - .name("side_options")) - ) + .name("side_options"))) .child(new SingleChildWidget<>() .coverChildren() .padding(7) @@ -278,7 +280,8 @@ public static class Recipes { .itemIn(Items.GOLD_INGOT, 4) .itemOut(Items.NETHER_STAR)); - // add (many) more recipes with (consistent) random inputs and outputs to try to overflow the cache for testing + // add (many) more recipes with (consistent) random inputs and outputs to try to overflow the cache for + // testing final int VERY_MANY_RECIPES = 256; RandomSource rng = RandomSource.create(""" // chosen by fair dice roll. @@ -295,20 +298,23 @@ public static class Recipes { while (recipe.inItems.size() < inItems) { BuiltInRegistries.ITEM.getRandom(rng).ifPresent(item -> { ItemStack stack = item.value().getDefaultInstance(); - stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, stack.getMaxStackSize())); + stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, + stack.getMaxStackSize())); recipe.itemIn(stack); }); } while (recipe.outItems.size() < outItems) { BuiltInRegistries.ITEM.getRandom(rng).ifPresent(item -> { ItemStack stack = item.value().getDefaultInstance(); - stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, stack.getMaxStackSize())); + stack.setCount(Mth.clamp((int) (rng.nextGaussian() * stack.getMaxStackSize()), 0, + stack.getMaxStackSize())); recipe.itemOut(stack); }); } while (recipe.inFluids.size() < inFluids) { BuiltInRegistries.FLUID.getRandom(rng).ifPresent(fluid -> { - int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, FLUID_SLOT_CAPACITY); + int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, + FLUID_SLOT_CAPACITY); if (amount == 0) return; recipe.fluidIn(fluid.value(), amount); @@ -316,7 +322,8 @@ public static class Recipes { } while (recipe.outFluids.size() < outFluids) { BuiltInRegistries.FLUID.getRandom(rng).ifPresent(fluid -> { - int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, FLUID_SLOT_CAPACITY); + int amount = Mth.clamp((int) (rng.nextGaussian() * FLUID_SLOT_CAPACITY), 0, + FLUID_SLOT_CAPACITY); if (amount == 0) return; recipe.fluidOut(fluid.value(), amount); @@ -327,7 +334,8 @@ public static class Recipes { } }); - public static Recipe findRecipe(IItemHandler inputItems, IFluidHandler inputFluids, @Nullable Recipe lastRecipe) { + public static Recipe findRecipe(IItemHandler inputItems, IFluidHandler inputFluids, + @Nullable Recipe lastRecipe) { if (lastRecipe != null && lastRecipe.startRecipe(inputItems, inputFluids, true)) return lastRecipe; for (Recipe recipe : list) { if (recipe.startRecipe(inputItems, inputFluids, true)) { @@ -368,8 +376,10 @@ private static boolean extract(FluidStack stack, IFluidHandler handler, boolean return false; } - public static IWidget buildMachineUI(ModularPanel panel, IItemHandlerModifiable inItems, IItemHandlerModifiable outItems, - IMultiTankFluidHandler inFluids, IMultiTankFluidHandler outFluids, IDoubleValue progress, + public static IWidget buildMachineUI(ModularPanel panel, IItemHandlerModifiable inItems, + IItemHandlerModifiable outItems, + IMultiTankFluidHandler inFluids, IMultiTankFluidHandler outFluids, + IDoubleValue progress, final boolean isRecipeViewerUI) { var val = new StringValue("Option 1"); IPanelHandler panelHandler = IPanelHandler.simple(panel, (parent, player) -> { @@ -385,7 +395,8 @@ public static IWidget buildMachineUI(ModularPanel panel, IItemHandlerModifiab .option("Option 1") .option("Option 2") .option("Option 3") - .optionToWidget((s, b) -> Text.str(s).asWidget().center().color(Color.WHITE.main).shadow(true).padding(2))) + .optionToWidget((s, b) -> Text.str(s).asWidget().center().color(Color.WHITE.main) + .shadow(true).padding(2))) .child(new ButtonWidget<>() .size(70, 14) .overlay(Text.str("Sub panel")) diff --git a/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java b/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java index b71b2d0b..98191ff9 100644 --- a/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java +++ b/src/main/java/brachy/modularui/test/TestRecipeViewerGuis.java @@ -2,22 +2,32 @@ import brachy.modularui.ModularUI; import brachy.modularui.api.widget.IWidget; +import brachy.modularui.integration.emi.recipe.ModularUIEmiCategory; import brachy.modularui.integration.emi.recipe.ModularUIEmiRecipe; import brachy.modularui.integration.jei.ModularUIJeiPlugin; import brachy.modularui.integration.jei.recipe.ModularUIJeiCategory; import brachy.modularui.integration.recipeviewer.RecipeSlotRole; import brachy.modularui.integration.recipeviewer.handlers.IngredientProvider; -import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; import brachy.modularui.integration.rei.recipe.ModularUIReiCategory; -import brachy.modularui.integration.emi.recipe.ModularUIEmiCategory; +import brachy.modularui.integration.rei.recipe.ModularUIReiDisplay; +import brachy.modularui.screen.ModularPanel; import brachy.modularui.utils.handlers.fluid.EmptyFluidTank; import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; import brachy.modularui.utils.handlers.fluid.MultiTankFluidHandler; -import brachy.modularui.screen.ModularPanel; import brachy.modularui.value.DoubleValue; import brachy.modularui.widgets.slot.FluidSlot; import brachy.modularui.widgets.slot.ItemSlot; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.wrapper.EmptyItemHandler; + import dev.emi.emi.api.EmiApi; import dev.emi.emi.api.EmiRegistry; import dev.emi.emi.api.recipe.EmiRecipeCategory; @@ -33,24 +43,13 @@ import me.shedaniel.rei.api.common.util.EntryIngredients; import me.shedaniel.rei.api.common.util.EntryStacks; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.recipe.RecipeType; import mezz.jei.api.registration.IRecipeCatalystRegistration; import mezz.jei.api.registration.IRecipeCategoryRegistration; import mezz.jei.api.registration.IRecipeRegistration; -import mezz.jei.api.neoforge.NeoForgeTypes; - -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.neoforged.neoforge.common.Tags; -import net.neoforged.neoforge.fluids.FluidStack; -import net.neoforged.neoforge.fluids.IFluidTank; -import net.neoforged.neoforge.items.IItemHandlerModifiable; -import net.neoforged.neoforge.items.wrapper.EmptyItemHandler; - import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; @@ -63,12 +62,14 @@ public class TestRecipeViewerGuis { private static final IItemHandlerModifiable EMPTY_INFINITE_ITEM_HANDLER = new EmptyItemHandler() { + @Override public int getSlots() { return Integer.MAX_VALUE; // pls don't iterate UwU } }; private static final IMultiTankFluidHandler EMPTY_MULTI_TANK_FLUID_HANDLER = new MultiTankFluidHandler() { + @Override public int getTanks() { return Integer.MAX_VALUE; // pls don't iterate UwU @@ -106,8 +107,11 @@ public static IWidget buildViewerUI(TestMachine.Recipe recipe) { return slot.toRecipeViewerSlot() .value(fluid) .tooltipBuilder(tooltip -> { - tooltip.addLine(Component.literal("Amount: " + fluid.getAmount() + " L").withStyle(ChatFormatting.BLUE)); - tooltip.addLine(Component.literal("Temperature: " + fluid.getFluid().getFluidType().getTemperature() + " K").withStyle(ChatFormatting.RED)); + tooltip.addLine(Component.literal("Amount: " + fluid.getAmount() + " L") + .withStyle(ChatFormatting.BLUE)); + tooltip.addLine(Component + .literal("Temperature: " + fluid.getFluid().getFluidType().getTemperature() + " K") + .withStyle(ChatFormatting.RED)); String liquid = !fluid.getFluid().is(Tags.Fluids.GASEOUS) ? "liquid" : "gas"; tooltip.addLine(Component.literal("State: " + liquid).withStyle(ChatFormatting.GREEN)); }); @@ -131,7 +135,8 @@ public static void openTestRecipeViewerCategory() { public static class EMI { - public static final EmiRecipeCategory CATEGORY = new ModularUIEmiCategory(ModularUI.id("machine"), EmiStack.of(TestRegistration.TEST_MACHINE_BLOCK_ITEM.get())); + public static final EmiRecipeCategory CATEGORY = new ModularUIEmiCategory(ModularUI.id("machine"), + EmiStack.of(TestRegistration.TEST_MACHINE_BLOCK_ITEM.get())); public static void openRecipeCategory() { EmiApi.displayRecipeCategory(CATEGORY); @@ -147,8 +152,10 @@ public static void register(EmiRegistry registry) { public static class RecipeDisplay extends ModularUIEmiRecipe { private final TestMachine.Recipe recipe; - @Getter private final List inputs = new ArrayList<>(); - @Getter private final List outputs = new ArrayList<>(); + @Getter + private final List inputs = new ArrayList<>(); + @Getter + private final List outputs = new ArrayList<>(); public RecipeDisplay(Supplier widgetSupplier, TestMachine.Recipe recipe) { super(recipe.id, widgetSupplier); @@ -168,7 +175,8 @@ public EmiRecipeCategory getCategory() { public static class JEI { - public static final RecipeType RECIPE_TYPE = new RecipeType<>(ModularUI.id("machine"), TestMachine.Recipe.class); + public static final RecipeType RECIPE_TYPE = new RecipeType<>(ModularUI.id("machine"), + TestMachine.Recipe.class); public static void openRecipeCategory() { ModularUIJeiPlugin.getRuntime().getRecipesGui().showTypes(List.of(RECIPE_TYPE)); @@ -209,7 +217,8 @@ public int getMaxHeight() { } @Override - public void setupRecipeIngredients(IRecipeLayoutBuilder builder, TestMachine.Recipe recipe, IFocusGroup focuses) { + public void setupRecipeIngredients(IRecipeLayoutBuilder builder, TestMachine.Recipe recipe, + IFocusGroup focuses) { builder.addSlot(RecipeIngredientRole.INPUT) .addItemStacks(recipe.inItems) .addIngredients(NeoForgeTypes.FLUID_STACK, recipe.inFluids); @@ -247,8 +256,10 @@ public static void registerDisplay(DisplayRegistry registry) { public static class RecipeDisplay extends ModularUIReiDisplay { private final TestMachine.Recipe recipe; - @Getter private final List inputEntries = new ArrayList<>(); - @Getter private final List outputEntries = new ArrayList<>(); + @Getter + private final List inputEntries = new ArrayList<>(); + @Getter + private final List outputEntries = new ArrayList<>(); public RecipeDisplay(Supplier recipeUI, TestMachine.Recipe recipe) { super(recipe.id, recipeUI, CATEGORY); diff --git a/src/main/java/brachy/modularui/test/TestRegistration.java b/src/main/java/brachy/modularui/test/TestRegistration.java index f0d386ca..72e7c106 100644 --- a/src/main/java/brachy/modularui/test/TestRegistration.java +++ b/src/main/java/brachy/modularui/test/TestRegistration.java @@ -2,7 +2,6 @@ import brachy.modularui.ModularUI; -import net.minecraft.core.Direction; import net.minecraft.core.registries.Registries; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTabs; @@ -59,12 +58,14 @@ public static void registerCapabilities(RegisterCapabilitiesEvent event) { event.registerItem(Capabilities.ItemHandler.ITEM, (stack, ctx) -> { return new ItemStackHandler(4); }, TestRegistration.TEST_ITEM.get()); - event.registerBlockEntity(Capabilities.ItemHandler.BLOCK, TestRegistration.TEST_MACHINE_BLOCK_ENTITY.get(), (machine, dir) -> { - return machine.getItemHandler(); - }); - event.registerBlockEntity(Capabilities.FluidHandler.BLOCK, TestRegistration.TEST_MACHINE_BLOCK_ENTITY.get(), (machine, dir) -> { - return machine.getFluidHandler(); - }); + event.registerBlockEntity(Capabilities.ItemHandler.BLOCK, TestRegistration.TEST_MACHINE_BLOCK_ENTITY.get(), + (machine, dir) -> { + return machine.getItemHandler(); + }); + event.registerBlockEntity(Capabilities.FluidHandler.BLOCK, TestRegistration.TEST_MACHINE_BLOCK_ENTITY.get(), + (machine, dir) -> { + return machine.getFluidHandler(); + }); } public static void register(IEventBus modBus) { diff --git a/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java b/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java index 417840c2..97c1acb0 100755 --- a/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java +++ b/src/main/java/brachy/modularui/theme/ReloadThemeEvent.java @@ -4,6 +4,7 @@ /** * This event is invoked when themes are reloaded, but not on startup. - * Do not use this to register themes. Use {@link net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent FMLConstructModEvent} instead. + * Do not use this to register themes. Use {@link net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent + * FMLConstructModEvent} instead. */ public class ReloadThemeEvent extends Event {} diff --git a/src/main/java/brachy/modularui/theme/SelectableTheme.java b/src/main/java/brachy/modularui/theme/SelectableTheme.java index b67841bc..8e0a88e3 100755 --- a/src/main/java/brachy/modularui/theme/SelectableTheme.java +++ b/src/main/java/brachy/modularui/theme/SelectableTheme.java @@ -71,7 +71,7 @@ public int getSelectedIconColor() { } public static class Builder> - extends WidgetThemeBuilder { + extends WidgetThemeBuilder { public B selectedColor(int color) { add(IThemeApi.SELECTED_COLOR, ThemeBuilder.colorJson(color)); diff --git a/src/main/java/brachy/modularui/theme/TextFieldTheme.java b/src/main/java/brachy/modularui/theme/TextFieldTheme.java index 17db0a73..7e556b05 100755 --- a/src/main/java/brachy/modularui/theme/TextFieldTheme.java +++ b/src/main/java/brachy/modularui/theme/TextFieldTheme.java @@ -34,7 +34,7 @@ public WidgetTheme withNoHoverBackground() { } public static class Builder> - extends WidgetThemeBuilder { + extends WidgetThemeBuilder { public B markedColor(int markedColor) { add(IThemeApi.MARKED_COLOR, ThemeBuilder.colorJson(markedColor)); diff --git a/src/main/java/brachy/modularui/theme/ThemeAPI.java b/src/main/java/brachy/modularui/theme/ThemeAPI.java index 78bc0e79..230344e8 100644 --- a/src/main/java/brachy/modularui/theme/ThemeAPI.java +++ b/src/main/java/brachy/modularui/theme/ThemeAPI.java @@ -61,7 +61,8 @@ public List getJavaDefaultThemes(String id) { } @Override - public ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, @Nullable String fallbackTheme) { + public ITheme getThemeForScreen(String owner, String name, @Nullable String panel, @Nullable String defaultTheme, + @Nullable String fallbackTheme) { String theme = getThemeIdForScreen(owner, name, panel); if (theme != null) return getTheme(theme); if (defaultTheme != null) return getTheme(defaultTheme); @@ -100,7 +101,9 @@ public void registerThemeForScreen(String screen, String theme) { @SuppressWarnings("unchecked") @Override - public WidgetThemeKey registerWidgetTheme(String id, T defaultTheme, T defaultHoverTheme, WidgetThemeMerger merger, WidgetThemeCodec codec) { + public WidgetThemeKey registerWidgetTheme(String id, T defaultTheme, T defaultHoverTheme, + WidgetThemeMerger merger, + WidgetThemeCodec codec) { Objects.requireNonNull(id, "Id for widget theme must not be null"); Objects.requireNonNull(defaultTheme, "Default widget theme must not be null, but is null for id '" + id + "'."); Objects.requireNonNull(merger, "Merger for widget theme must not be null, but is null for id '" + id + "'."); diff --git a/src/main/java/brachy/modularui/theme/ThemeBuilder.java b/src/main/java/brachy/modularui/theme/ThemeBuilder.java index f64a0e13..deec4410 100755 --- a/src/main/java/brachy/modularui/theme/ThemeBuilder.java +++ b/src/main/java/brachy/modularui/theme/ThemeBuilder.java @@ -115,7 +115,7 @@ public B background(WidgetThemeKey widgetTheme, String textureId) { } public B background(WidgetThemeKey widgetTheme, JsonBuilder builder) { - if (builder instanceof WidgetThemeBuilder) { + if (builder instanceof WidgetThemeBuilder) { throw new IllegalArgumentException("Did you mean to call .widgetTheme() instead of .background()?"); } mergeAdd(widgetTheme.getFullName(), @@ -134,7 +134,7 @@ public B hoverBackground(WidgetThemeKey widgetTheme, String textureId) { } public B hoverBackground(WidgetThemeKey widgetTheme, JsonBuilder builder) { - if (builder instanceof WidgetThemeBuilder) { + if (builder instanceof WidgetThemeBuilder) { throw new IllegalArgumentException("Did you mean to call .widgetTheme() instead of .hoverBackground()?"); } mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, @@ -148,7 +148,8 @@ public B color(WidgetThemeKey widgetTheme, int v) { } public B hoverColor(WidgetThemeKey widgetTheme, int v) { - mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, new JsonBuilder().add(IThemeApi.COLOR, colorJson(v))); + mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, + new JsonBuilder().add(IThemeApi.COLOR, colorJson(v))); return getThis(); } @@ -158,7 +159,8 @@ public B textColor(WidgetThemeKey widgetTheme, int v) { } public B textHoverColor(WidgetThemeKey widgetTheme, int v) { - mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, new JsonBuilder().add(IThemeApi.TEXT_COLOR, colorJson(v))); + mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, + new JsonBuilder().add(IThemeApi.TEXT_COLOR, colorJson(v))); return getThis(); } @@ -178,7 +180,8 @@ public B iconColor(WidgetThemeKey widgetTheme, int v) { } public B iconHoverColor(WidgetThemeKey widgetTheme, int v) { - mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, new JsonBuilder().add(IThemeApi.ICON_COLOR, colorJson(v))); + mergeAdd(widgetTheme.getFullName() + IThemeApi.HOVER_SUFFIX, + new JsonBuilder().add(IThemeApi.ICON_COLOR, colorJson(v))); return getThis(); } diff --git a/src/main/java/brachy/modularui/theme/ThemeManager.java b/src/main/java/brachy/modularui/theme/ThemeManager.java index ab025006..0d322510 100755 --- a/src/main/java/brachy/modularui/theme/ThemeManager.java +++ b/src/main/java/brachy/modularui/theme/ThemeManager.java @@ -13,7 +13,6 @@ import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.SimplePreparableReloadListener; import net.minecraft.util.profiling.ProfilerFiller; -import com.mojang.serialization.JsonOps; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.neoforge.common.NeoForge; @@ -21,6 +20,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import com.mojang.serialization.JsonOps; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -268,7 +268,7 @@ private static void loadScreenThemes(JsonObject json) { private static void validateJsonScreenThemes() { for (ObjectIterator> iterator = ThemeAPI.INSTANCE.jsonScreenThemes - .object2ObjectEntrySet().fastIterator(); iterator.hasNext(); ) { + .object2ObjectEntrySet().fastIterator(); iterator.hasNext();) { Map.Entry entry = iterator.next(); if (!ThemeAPI.INSTANCE.hasTheme(entry.getValue())) { ModularUI.LOGGER.error("Tried to register theme '{}' for screen '{}', but theme does not exist", @@ -289,7 +289,7 @@ private ThemeJson(String id, List jsons, boolean override) { this.id = id; this.override = override; String p = null; - for (ListIterator iterator = jsons.listIterator(jsons.size()); iterator.hasPrevious(); ) { + for (ListIterator iterator = jsons.listIterator(jsons.size()); iterator.hasPrevious();) { JsonObject json = iterator.previous(); if (json.has(IThemeApi.PARENT)) { p = json.get(IThemeApi.PARENT).getAsString(); @@ -321,7 +321,8 @@ private Theme deserialize() { WidgetThemeMap widgetThemes = new WidgetThemeMap(); WidgetThemeEntry parentWidgetTheme = parent.getFallbackEntry(); // fallback theme of parent // fallback theme of new theme - var incompleteFallbackJson = ImmutableJson.of(jsonBuilder.getJson()); // themes should only inherit values which are declared here + var incompleteFallbackJson = ImmutableJson.of(jsonBuilder.getJson()); // themes should only inherit values + // which are declared here var fallbackJson = IThemeApi.FALLBACK.getMerger().merge( jsonBuilder.getJson(), ThemeManager.jsons.get(IThemeApi.FALLBACK, parentWidgetTheme.theme()), @@ -375,9 +376,11 @@ private void parse(WidgetThemeMap map, ITheme parent, Wi if (key.isSubWidgetTheme()) fallback = ImmutableJson.EMPTY; ImmutableJson widgetThemeJson; if (rawWidgetThemeJson != null) { - T parentWidgetTheme = key.isSubWidgetTheme() ? map.getTheme(key.getParent()).theme() : parent.getWidgetThemeEntry(key).theme(); + T parentWidgetTheme = key.isSubWidgetTheme() ? map.getTheme(key.getParent()).theme() : + parent.getWidgetThemeEntry(key).theme(); // sub widget themes strictly only inherit from their parent widget theme and not the parent theme - widgetThemeJson = ImmutableJson.of(merger.merge(rawWidgetThemeJson, ThemeManager.jsons.get(key, parentWidgetTheme), fallback)); + widgetThemeJson = ImmutableJson + .of(merger.merge(rawWidgetThemeJson, ThemeManager.jsons.get(key, parentWidgetTheme), fallback)); } else { widgetThemeJson = ThemeManager.jsons.get(key, parent.getWidgetThemeEntry(key).theme()); } @@ -389,12 +392,15 @@ private void parse(WidgetThemeMap map, ITheme parent, Wi } // only inherit from the widget theme if it was actually defined, otherwise use parent - ImmutableJson parentWidgetHoverTheme = definedStandard ? widgetThemeJson : ThemeManager.jsons.get(key, parent.getWidgetThemeEntry(key).hoverTheme()); + ImmutableJson parentWidgetHoverTheme = definedStandard ? widgetThemeJson : + ThemeManager.jsons.get(key, parent.getWidgetThemeEntry(key).hoverTheme()); JsonObject widgetThemeHover = merger.merge(widgetThemeHoverJson, parentWidgetHoverTheme, fallback); var immutableHoverWidgetTheme = ImmutableJson.of(widgetThemeHover); - T widgetThemeInstance = key.getCodec().codec().parse(JsonOps.INSTANCE, widgetThemeJson.toJson()).getOrThrow(); - T widgetThemeHoverInstance = key.getCodec().codec().parse(JsonOps.INSTANCE, immutableHoverWidgetTheme.toJson()).getOrThrow(); + T widgetThemeInstance = key.getCodec().codec().parse(JsonOps.INSTANCE, widgetThemeJson.toJson()) + .getOrThrow(); + T widgetThemeHoverInstance = key.getCodec().codec() + .parse(JsonOps.INSTANCE, immutableHoverWidgetTheme.toJson()).getOrThrow(); map.register(key, widgetThemeInstance, widgetThemeHoverInstance); } diff --git a/src/main/java/brachy/modularui/theme/WidgetTheme.java b/src/main/java/brachy/modularui/theme/WidgetTheme.java index 322040d3..b0f8ca66 100755 --- a/src/main/java/brachy/modularui/theme/WidgetTheme.java +++ b/src/main/java/brachy/modularui/theme/WidgetTheme.java @@ -14,15 +14,21 @@ public static WidgetThemeEntry getDefault() { return ThemeAPI.DEFAULT_THEME.getFallbackEntry(); } - @Getter private final int defaultWidth; - @Getter private final int defaultHeight; + @Getter + private final int defaultWidth; + @Getter + private final int defaultHeight; @Getter @Nullable private final IDrawable background; - @Getter private final int color; - @Getter private final int textColor; - @Getter private final boolean textShadow; - @Getter private final int iconColor; + @Getter + private final int color; + @Getter + private final int textColor; + @Getter + private final boolean textShadow; + @Getter + private final int iconColor; public static WidgetTheme whiteTextShadow(int defaultWidth, int defaultHeight, @Nullable IDrawable background) { return new WidgetTheme(defaultWidth, defaultHeight, background, Color.WHITE.main, diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java b/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java index a7375aa0..276592c0 100644 --- a/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeCodec.java @@ -5,7 +5,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; - import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.AccessLevel; import lombok.Getter; @@ -43,12 +42,12 @@ public DataResult decode(DynamicOps ops, MapLike input) { List args = new ArrayList<>(); this.fields.forEach(f -> args.add(f.decode(ops, map, errors))); if (!errors.isEmpty()) { - return DataResult.error(() -> - String.format("Errors while decoding widget theme: %s", errors)); + return DataResult.error(() -> String.format("Errors while decoding widget theme: %s", errors)); } try { return DataResult.success(this.ctor.newInstance(args.toArray(Object[]::new))); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | + IllegalArgumentException e) { return DataResult.error(e::getMessage); } } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java b/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java index 6f3e0689..3d260a09 100755 --- a/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeEntry.java @@ -12,10 +12,10 @@ * @see WidgetThemeKey * @see ITheme * - * @param key The {@link WidgetThemeKey} which this theme data is for. - * @param theme The theme data. + * @param key The {@link WidgetThemeKey} which this theme data is for. + * @param theme The theme data. * @param hoverTheme Theme data to be used when this widget is being hovered over. - * @param The class of the theme data. + * @param The class of the theme data. */ public record WidgetThemeEntry(WidgetThemeKey key, T theme, T hoverTheme) { @@ -44,6 +44,7 @@ public void encode(DynamicOps ops, RecordBuilder mapBuilder, boolean f mapBuilder.add(this.key.getFullName(), this.key.getCodec().codec().encodeStart(ops, this.theme)); } if (this.theme == this.hoverTheme) return; - mapBuilder.add(this.key.getFullName() + IThemeApi.HOVER_SUFFIX, this.key.getCodec().codec().encodeStart(ops, this.hoverTheme)); + mapBuilder.add(this.key.getFullName() + IThemeApi.HOVER_SUFFIX, + this.key.getCodec().codec().encodeStart(ops, this.hoverTheme)); } } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeField.java b/src/main/java/brachy/modularui/theme/WidgetThemeField.java index 264ae95f..70eab730 100644 --- a/src/main/java/brachy/modularui/theme/WidgetThemeField.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeField.java @@ -9,7 +9,8 @@ import java.util.List; import java.util.Map; -public record WidgetThemeField(String name, Class type, Codec codec, FieldReader fieldReader, +public record WidgetThemeField(String name, Class type, Codec codec, + FieldReader fieldReader, boolean canFallback) { void encode(T widgetTheme, DynamicOps ops, RecordBuilder mapBuilder) { @@ -27,7 +28,8 @@ V decode(DynamicOps ops, Map map, List errors) { J element = map.get(name()); if (element == null) { if (!map.containsKey(name())) { - errors.add(String.format("Field '%s' in widget theme of type %s was not found", name(), type().getSimpleName())); + errors.add(String.format("Field '%s' in widget theme of type %s was not found", name(), + type().getSimpleName())); } return null; } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeKey.java b/src/main/java/brachy/modularui/theme/WidgetThemeKey.java index 4da3b396..2f74a6e1 100755 --- a/src/main/java/brachy/modularui/theme/WidgetThemeKey.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeKey.java @@ -3,11 +3,9 @@ import brachy.modularui.api.ITheme; import brachy.modularui.utils.serialization.codec.CodecUtil; -import net.minecraft.util.ExtraCodecs; +import com.google.gson.JsonObject; import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; - -import com.google.gson.JsonObject; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import lombok.Getter; import org.jetbrains.annotations.NotNull; @@ -17,7 +15,8 @@ import java.util.Objects; /** - * A widget theme key represents a specific type of data (e.g. item slot theme, fluid slot theme, button theme, etc), which a theme may contain.
+ * A widget theme key represents a specific type of data (e.g. item slot theme, fluid slot theme, button theme, etc), + * which a theme may contain.
* The theme key contains a codec for serialising this data, as well as the default.
* * @see WidgetThemeEntry @@ -28,7 +27,8 @@ public class WidgetThemeKey implements Comparable> { private static final Map> KEYS = new Object2ReferenceOpenHashMap<>(); - public static final Codec> CODEC = CodecUtil.chainedCodec(CodecUtil.nullCodec(), Codec.stringResolver(WidgetThemeKey::getFullName, KEYS::get)); + public static final Codec> CODEC = CodecUtil.chainedCodec(CodecUtil.nullCodec(), + Codec.stringResolver(WidgetThemeKey::getFullName, KEYS::get)); @Nullable public static WidgetThemeKey getFromFullName(String key) { @@ -38,21 +38,28 @@ public static WidgetThemeKey getFromFullName(String key) { @Nullable @Getter private final WidgetThemeKey parent; - @Getter private final Class type; - @Getter private final String name; + @Getter + private final Class type; + @Getter + private final String name; @Nullable @Getter private final String subName; - @Getter private final T defaultValue; - @Getter private final T defaultHoverValue; - @Getter private final WidgetThemeMerger merger; - @Getter private final WidgetThemeCodec codec; + @Getter + private final T defaultValue; + @Getter + private final T defaultHoverValue; + @Getter + private final WidgetThemeMerger merger; + @Getter + private final WidgetThemeCodec codec; WidgetThemeKey(Class type, String name, T defaultValue, WidgetThemeMerger merger, WidgetThemeCodec codec) { this(type, name, defaultValue, defaultValue, merger, codec); } - WidgetThemeKey(Class type, String name, T defaultValue, T defaultHoverValue, WidgetThemeMerger merger, WidgetThemeCodec codec) { + WidgetThemeKey(Class type, String name, T defaultValue, T defaultHoverValue, WidgetThemeMerger merger, + WidgetThemeCodec codec) { this(null, type, name, null, defaultValue, defaultHoverValue, merger, codec); } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java b/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java index 75b22ff0..071e6eb3 100755 --- a/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeKeyBuilder.java @@ -45,26 +45,31 @@ public WidgetThemeKeyBuilder fieldsOf(WidgetThemeKey key) { return this; } - public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, FieldReader fieldReader) { + public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, + FieldReader fieldReader) { return field(name, type, codec, fieldReader, false); } - public WidgetThemeKeyBuilder fallbackField(String name, Class type, Codec codec, FieldReader fieldReader) { + public WidgetThemeKeyBuilder fallbackField(String name, Class type, Codec codec, + FieldReader fieldReader) { return field(name, type, codec, fieldReader, true); } /** - * Adds a field to the codec. The widget theme must have a public constructor with all the fields in the same order they were added. + * Adds a field to the codec. The widget theme must have a public constructor with all the fields in the same order + * they were added. * The constructor is found and used via reflection. * * @param name name of the field, used to read and write in JSON * @param type type of the field in the constructor, must be exact * @param codec codec for this field * @param fieldReader reads the field from a widget theme - * @param canFallback determines if values are inherited from parent or fallback first, if this is true fallback is used first, + * @param canFallback determines if values are inherited from parent or fallback first, if this is true fallback is + * used first, * but can be disabled individually via the "inherited" property in JSON */ - public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, FieldReader fieldReader, boolean canFallback) { + public WidgetThemeKeyBuilder field(String name, Class type, Codec codec, FieldReader fieldReader, + boolean canFallback) { this.fields.add(new WidgetThemeField<>(name, type, codec, fieldReader, canFallback)); return this; } @@ -89,16 +94,19 @@ public WidgetThemeKey register() { merger = (WidgetThemeMerger) this.parser.getMerger(); } } - if (this.fields.isEmpty() && (merger == null || codec == null)) throw new IllegalArgumentException("No fields for codec provided!"); + if (this.fields.isEmpty() && (merger == null || codec == null)) + throw new IllegalArgumentException("No fields for codec provided!"); if (merger == null) merger = new WidgetThemeMerger<>(this.fields); if (codec == null) { Constructor ctor; Class[] types = this.fields.stream().map(WidgetThemeField::type).toArray(Class[]::new); try { - ctor = this.type.getDeclaredConstructor(this.fields.stream().map(WidgetThemeField::type).toArray(Class[]::new)); + ctor = this.type + .getDeclaredConstructor(this.fields.stream().map(WidgetThemeField::type).toArray(Class[]::new)); } catch (NoSuchMethodException e) { String sTypes = Arrays.stream(types).map(Class::getSimpleName).reduce("", (a, b) -> a + b + ", "); - throw new IllegalArgumentException("No constructor found for the fields with the given types in that order. Types: " + sTypes); + throw new IllegalArgumentException( + "No constructor found for the fields with the given types in that order. Types: " + sTypes); } codec = new WidgetThemeCodec<>(this.type, this.fields, ctor); } diff --git a/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java b/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java index 802f56f4..e0bed769 100644 --- a/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java +++ b/src/main/java/brachy/modularui/theme/WidgetThemeMerger.java @@ -27,7 +27,8 @@ public JsonObject merge(JsonObject input, ImmutableJson parent, ImmutableJson fa return input; } - private void mergeField(WidgetThemeField field, JsonObject input, ImmutableJson parent, ImmutableJson fallback, JsonElement inheritsList) { + private void mergeField(WidgetThemeField field, JsonObject input, ImmutableJson parent, + ImmutableJson fallback, JsonElement inheritsList) { var key = field.name(); if (input.has(key)) return; if (field.canFallback() && !inherits(inheritsList, key) && fallback.has(key)) { diff --git a/src/main/java/brachy/modularui/utils/Alignment.java b/src/main/java/brachy/modularui/utils/Alignment.java index ec46d7db..1fb878f2 100644 --- a/src/main/java/brachy/modularui/utils/Alignment.java +++ b/src/main/java/brachy/modularui/utils/Alignment.java @@ -2,12 +2,11 @@ import brachy.modularui.utils.serialization.codec.CodecUtil; -import net.minecraft.util.ExtraCodecs; import net.minecraft.util.StringRepresentable; -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; import com.google.common.base.CaseFormat; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.AccessLevel; import lombok.Getter; @@ -23,14 +22,15 @@ public class Alignment { private static final Codec CODEC_OF_INSTANCE = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("x").forGetter(Alignment::getX), - Codec.FLOAT.fieldOf("y").forGetter(Alignment::getY) - ).apply(instance, Alignment::new)); + Codec.FLOAT.fieldOf("y").forGetter(Alignment::getY)).apply(instance, Alignment::new)); private static final Codec CODEC_OF_NAME = Codec.stringResolver(Alignment::getName, ALIGNMENT_MAP::get); public static final Codec CODEC = CodecUtil.chainedCodec(CODEC_OF_NAME, CODEC_OF_INSTANCE); - @Getter public final float x, y; - @Getter(AccessLevel.PRIVATE) private final String name; + @Getter + public final float x, y; + @Getter(AccessLevel.PRIVATE) + private final String name; public static final Alignment TopLeft = new Alignment(0, 0, "TopLeft"); public static final Alignment TopCenter = new Alignment(0.5f, 0, "TopCenter"); diff --git a/src/main/java/brachy/modularui/utils/Color.java b/src/main/java/brachy/modularui/utils/Color.java index a2d370bb..d3f4ff6c 100644 --- a/src/main/java/brachy/modularui/utils/Color.java +++ b/src/main/java/brachy/modularui/utils/Color.java @@ -5,14 +5,14 @@ import brachy.modularui.utils.serialization.codec.CodecUtil; import net.minecraft.util.Mth; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.codecs.RecordCodecBuilder; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import com.google.gson.JsonObject; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.Locale; import java.util.Random; @@ -610,7 +610,7 @@ public static int withBlack(int argb, float black) { * @return rgba as an array [red, green, blue] */ public static int[] getRGBValues(int argb) { - return new int[]{getRed(argb), getGreen(argb), getBlue(argb)}; + return new int[] { getRed(argb), getGreen(argb), getBlue(argb) }; } /** @@ -619,7 +619,7 @@ public static int[] getRGBValues(int argb) { * @return rgba as an array [red, green, blue, alpha] */ public static int[] getARGBValues(int argb) { - return new int[]{getRed(argb), getGreen(argb), getBlue(argb), getAlpha(argb)}; + return new int[] { getRed(argb), getGreen(argb), getBlue(argb), getAlpha(argb) }; } /** @@ -629,7 +629,7 @@ public static int[] getARGBValues(int argb) { * @return HSV values array */ public static float[] getHSVValues(int argb) { - return new float[]{getHue(argb), getHSVSaturation(argb), getValue(argb)}; + return new float[] { getHue(argb), getHSVSaturation(argb), getValue(argb) }; } /** @@ -639,7 +639,7 @@ public static float[] getHSVValues(int argb) { * @return HSL values array */ public static float[] getHSLValues(int argb) { - return new float[]{getHue(argb), getHSLSaturation(argb), getLightness(argb)}; + return new float[] { getHue(argb), getHSLSaturation(argb), getLightness(argb) }; } /** @@ -649,7 +649,7 @@ public static float[] getHSLValues(int argb) { * @return CMYK values array */ public static float[] getCMYKValues(int argb) { - return new float[]{getCyan(argb), getMagenta(argb), getYellow(argb), getBlack(argb)}; + return new float[] { getCyan(argb), getMagenta(argb), getYellow(argb), getBlack(argb) }; } /** @@ -836,11 +836,13 @@ public static void resetGlColor() { } public static int getLargestDiff(int argb1, int argb2) { - return Math.max(Math.abs(getRed(argb1) - getRed(argb2)), Math.max(Math.abs(getGreen(argb1) - getGreen(argb2)), Math.abs(getBlue(argb1) - getBlue(argb2)))); + return Math.max(Math.abs(getRed(argb1) - getRed(argb2)), + Math.max(Math.abs(getGreen(argb1) - getGreen(argb2)), Math.abs(getBlue(argb1) - getBlue(argb2)))); } public static float getLargestDiffFloat(int argb1, int argb2) { - return Math.max(Math.abs(getRedF(argb1) - getRedF(argb2)), Math.max(Math.abs(getGreenF(argb1) - getGreenF(argb2)), Math.abs(getBlueF(argb1) - getBlueF(argb2)))); + return Math.max(Math.abs(getRedF(argb1) - getRedF(argb2)), + Math.max(Math.abs(getGreenF(argb1) - getGreenF(argb2)), Math.abs(getBlueF(argb1) - getBlueF(argb2)))); } public static boolean areSameColor(int argb1, int argb2) { @@ -932,41 +934,39 @@ public static String componentToFullHexString(int component) { return s; } - public static final Codec CODEC_STRING = Codec.STRING.comapFlatMap(Color::parseString, c -> "#" + argbToFullHexString(c)); + public static final Codec CODEC_STRING = Codec.STRING.comapFlatMap(Color::parseString, + c -> "#" + argbToFullHexString(c)); public static final Codec CODEC_ARGB = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("r").forGetter(Color::getRedF), Codec.FLOAT.fieldOf("g").forGetter(Color::getGreenF), Codec.FLOAT.fieldOf("b").forGetter(Color::getBlueF), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::argb)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::argb)); public static final Codec CODEC_HSV = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("h").forGetter(Color::getHue), Codec.FLOAT.fieldOf("s").forGetter(Color::getHSVSaturation), Codec.FLOAT.fieldOf("v").forGetter(Color::getValue), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::ofHSV)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::ofHSV)); public static final Codec CODEC_HSL = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("h").forGetter(Color::getHue), Codec.FLOAT.fieldOf("s").forGetter(Color::getHSLSaturation), Codec.FLOAT.fieldOf("l").forGetter(Color::getLightness), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::ofHSL)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::ofHSL)); public static final Codec CODEC_CMYK = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("c").forGetter(Color::getCyan), Codec.FLOAT.fieldOf("m").forGetter(Color::getMagenta), Codec.FLOAT.fieldOf("y").forGetter(Color::getYellow), Codec.FLOAT.fieldOf("k").forGetter(Color::getBlack), - Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF) - ).apply(instance, Color::ofCMYK)); + Codec.FLOAT.optionalFieldOf("a", 1f).forGetter(Color::getAlphaF)).apply(instance, Color::ofCMYK)); /** * Encodes into hex string and decodes, hex string, arg obj, hsv obj, hsl obj, cmyk obj and then raw argb integer. */ - public static final Codec CODEC = CodecUtil.codecOf(CODEC_STRING, CODEC_STRING, CODEC_ARGB, CODEC_HSV, CODEC_HSL, CODEC_CMYK, Codec.INT); + public static final Codec CODEC = CodecUtil.codecOf(CODEC_STRING, CODEC_STRING, CODEC_ARGB, CODEC_HSV, + CODEC_HSL, CODEC_CMYK, Codec.INT); public static DataResult parseString(String colorString) { return parseString(colorString, WHITE.main); @@ -976,8 +976,10 @@ public static DataResult parseString(String colorString) { * Parses a color ARGB int from a string. * The string can be a number in decimal (no prefix), hexadecimal (0x, 0X or # prefix) or octal (0 prefix). * Otherwise, it can be a name from a {@link ColorShade} instance. The default instances can be found at the bottom - * of this class. These names can be suffixed with colon and a negative number for darker colors or positive number for brighter colors. - * The number is an index to an array with predefined shades. 0 is the main color. If no color for a name is found, the fallback value + * of this class. These names can be suffixed with colon and a negative number for darker colors or positive number + * for brighter colors. + * The number is an index to an array with predefined shades. 0 is the main color. If no color for a name is found, + * the fallback value * is returned. The shade index is clamped to valid values. *

* Example: "deep_purple:-3" returns 0xFF4527A0 @@ -1001,7 +1003,8 @@ public static DataResult parseString(String colorString, int fallback) return DataResult.success(color); } catch (NumberFormatException e) { String finalColorString = colorString; - return DataResult.error(() -> String.format("Failed to decode color of string '%s'.", finalColorString), fallback); + return DataResult.error(() -> String.format("Failed to decode color of string '%s'.", finalColorString), + fallback); } } @@ -1025,14 +1028,17 @@ public static DataResult parseString(String colorString, int fallback) if (colorShade != null) { if (fail != null) { String finalFail = fail; - return DataResult.error(() -> String.format("If the color is a word then after teh : must come a negative or positive integer, but got '%s'.", finalFail), colorShade.main); + return DataResult.error(() -> String.format( + "If the color is a word then after teh : must come a negative or positive integer, but got '%s'.", + finalFail), colorShade.main); } if (index == 0) return DataResult.success(colorShade.main); if (index > 0) return DataResult.success(colorShade.brighterSafe(index - 1)); return DataResult.success(colorShade.darkerSafe(-index - 1)); } String finalColorString1 = colorString; - return DataResult.error(() -> String.format("No color shade for name '%s' was found", finalColorString1), fallback); + return DataResult.error(() -> String.format("No color shade for name '%s' was found", finalColorString1), + fallback); } private static boolean hasRGB(JsonObject json) { diff --git a/src/main/java/brachy/modularui/utils/CursorHandler.java b/src/main/java/brachy/modularui/utils/CursorHandler.java index be31b6f0..68066275 100644 --- a/src/main/java/brachy/modularui/utils/CursorHandler.java +++ b/src/main/java/brachy/modularui/utils/CursorHandler.java @@ -95,7 +95,8 @@ public static long createSafeCursor(int shape) { try (GLFWErrorCallback ignored = GLFW.glfwSetErrorCallback(null)) { long cursor = GLFW.glfwCreateStandardCursor(shape); if (cursor == 0L) { // Couldn't load platform-specific default cursors - ModularUI.LOGGER.warn("GLFW: Failed to create standard cursor shape {}. Falling back to default pointer.", + ModularUI.LOGGER.warn( + "GLFW: Failed to create standard cursor shape {}. Falling back to default pointer.", shape); // TODO: Load custom textures return 0L; diff --git a/src/main/java/brachy/modularui/utils/FormattingUtil.java b/src/main/java/brachy/modularui/utils/FormattingUtil.java index ea74277a..0b743f66 100755 --- a/src/main/java/brachy/modularui/utils/FormattingUtil.java +++ b/src/main/java/brachy/modularui/utils/FormattingUtil.java @@ -75,7 +75,7 @@ private static String checkNumbers(String string, int startIndex) { * @param string Any string with ASCII characters. * @return A string that is all lowercase, with underscores inserted before word/number boundaries: * - *

+     *         
      *         
{@code "maragingSteel300" -> "maraging_steel_300"} *
{@code "modularui:maraging_steel_300" -> "modularui:maraging_steel_300"} *
{@code "maragingSteel_300" -> "maraging_steel_300"} @@ -299,7 +299,7 @@ public static String toRomanNumeral(int number) { * * @param string Any string with ASCII characters. * @return A string that is all lowercase, with underscores inserted before word/number boundaries: - * "maraging_steel_300" -> "maragingSteel300" + * "maraging_steel_300" -> "maragingSteel300" */ public static String lowerUnderscoreToUpperCamel(String string) { StringBuilder result = new StringBuilder(); diff --git a/src/main/java/brachy/modularui/utils/GradientUtil.java b/src/main/java/brachy/modularui/utils/GradientUtil.java index 7d1662b1..465941d8 100755 --- a/src/main/java/brachy/modularui/utils/GradientUtil.java +++ b/src/main/java/brachy/modularui/utils/GradientUtil.java @@ -23,7 +23,7 @@ public static float[] getRGB(int color) { float g = ((color >> 8) & 0xFF) / 255f; // noinspection PointlessBitwiseExpression float b = ((color >> 0) & 0xFF) / 255f; - return new float[]{r, g, b}; + return new float[] { r, g, b }; } public static int multiplyBlendWithAlpha(int c1, int c2) { @@ -123,7 +123,7 @@ public static float[] RGBtoHSL(int rgbColor) { s = (max - min) / (2 - max - min); } - return new float[]{h, s * 100, l * 100}; + return new float[] { h, s * 100, l * 100 }; } public static int toRGB(float[] hsv) { diff --git a/src/main/java/brachy/modularui/utils/ICopy.java b/src/main/java/brachy/modularui/utils/ICopy.java index 72af2270..16869b15 100644 --- a/src/main/java/brachy/modularui/utils/ICopy.java +++ b/src/main/java/brachy/modularui/utils/ICopy.java @@ -16,10 +16,12 @@ static ICopy immutable() { } @SuppressWarnings("unchecked") - static ICopy ofSerializer(StreamEncoder serializer, StreamDecoder deserializer) { + static ICopy ofSerializer(StreamEncoder serializer, + StreamDecoder deserializer) { return t -> { // the lowest subclass of ByteBuf is RegistryFriendlyByteBuf so this *should* work - RegistryFriendlyByteBuf buf = IRegistryFriendlyByteBufExtension.createEmpty(RegistryAccessContainer.current()); + RegistryFriendlyByteBuf buf = IRegistryFriendlyByteBufExtension + .createEmpty(RegistryAccessContainer.current()); serializer.encode((B) buf, t); return deserializer.decode((B) buf); }; diff --git a/src/main/java/brachy/modularui/utils/ImageUtil.java b/src/main/java/brachy/modularui/utils/ImageUtil.java index c09807bf..7759aa8a 100644 --- a/src/main/java/brachy/modularui/utils/ImageUtil.java +++ b/src/main/java/brachy/modularui/utils/ImageUtil.java @@ -90,7 +90,8 @@ public static boolean testImageSize(ResourceLocation resLoc, int width, int heig int w = ImageUtil.getWidth(size); int h = ImageUtil.getHeight(size); if (w != width || h != height) { - ModularUI.LOGGER.error("Image size is incorrect of image '{}'. Expected {}|{}, but actually is {}|{}", resLoc, + ModularUI.LOGGER.error("Image size is incorrect of image '{}'. Expected {}|{}, but actually is {}|{}", + resLoc, width, height, w, h); } else { ModularUI.LOGGER.info("Image '{}' has correct size", resLoc); @@ -179,6 +180,7 @@ private interface SizeParser { private enum ImageType implements SizeParser { PNG(8, 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) { + @Override public long parse(InputStream inputStream) throws IOException { DataInput dataInput = getDataInput(inputStream); @@ -188,6 +190,7 @@ public long parse(InputStream inputStream) throws IOException { } }, JPEG(2, 0xFF, 0xD8) { + @Override public long parse(InputStream inputStream) throws IOException { DataInput dis = getDataInput(inputStream); @@ -226,6 +229,7 @@ public long parse(InputStream inputStream) throws IOException { }, // 5th byte is variable -> only use the first 4 GIF(6, 0x47, 0x49, 0x46, 0x38) { + @Override public long parse(InputStream inputStream) throws IOException { return packSize(readLittleEndianShort(inputStream), readLittleEndianShort(inputStream)); diff --git a/src/main/java/brachy/modularui/utils/Interpolation.java b/src/main/java/brachy/modularui/utils/Interpolation.java index 75fe110c..259dc17a 100755 --- a/src/main/java/brachy/modularui/utils/Interpolation.java +++ b/src/main/java/brachy/modularui/utils/Interpolation.java @@ -13,24 +13,28 @@ public enum Interpolation implements IInterpolation, StringRepresentable { LINEAR("linear") { + @Override public float interpolate(float a, float b, float x) { return Interpolations.lerp(a, b, x); } }, QUAD_IN("quad_in") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * x * x; } }, QUAD_OUT("quad_out") { + @Override public float interpolate(float a, float b, float x) { return a - (b - a) * x * (x - 2); } }, QUAD_INOUT("quad_inout") { + @Override public float interpolate(float a, float b, float x) { x *= 2; @@ -43,12 +47,14 @@ public float interpolate(float a, float b, float x) { } }, CUBIC_IN("cubic_in") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * x * x * x; } }, CUBIC_OUT("cubic_out") { + @Override public float interpolate(float a, float b, float x) { x -= 1; @@ -56,6 +62,7 @@ public float interpolate(float a, float b, float x) { } }, CUBIC_INOUT("cubic_inout") { + @Override public float interpolate(float a, float b, float x) { x *= 2; @@ -68,18 +75,21 @@ public float interpolate(float a, float b, float x) { } }, EXP_IN("exp_in") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * (float) Math.pow(2, 10 * (x - 1)); } }, EXP_OUT("exp_out") { + @Override public float interpolate(float a, float b, float x) { return a + (b - a) * (float) (-Math.pow(2, -10 * x) + 1); } }, EXP_INOUT("exp_inout") { + @Override public float interpolate(float a, float b, float x) { if (x == 0) return a; @@ -96,6 +106,7 @@ public float interpolate(float a, float b, float x) { }, /* Following interpolations below were copied from: https://easings.net/ */ BACK_IN("back_in") { + @Override public float interpolate(float a, float b, float x) { final float c1 = 1.70158F; @@ -105,6 +116,7 @@ public float interpolate(float a, float b, float x) { } }, BACK_OUT("back_out") { + @Override public float interpolate(float a, float b, float x) { final float c1 = 1.70158F; @@ -114,6 +126,7 @@ public float interpolate(float a, float b, float x) { } }, BACK_INOUT("back_inout") { + @Override public float interpolate(float a, float b, float x) { final float c1 = 1.70158F; @@ -126,6 +139,7 @@ public float interpolate(float a, float b, float x) { } }, ELASTIC_IN("elastic_in") { + @Override public float interpolate(float a, float b, float x) { final float c4 = (2 * (float) Math.PI) / 3; @@ -137,6 +151,7 @@ public float interpolate(float a, float b, float x) { } }, ELASTIC_OUT("elastic_out") { + @Override public float interpolate(float a, float b, float x) { final float c4 = (2 * (float) Math.PI) / 3; @@ -148,25 +163,28 @@ public float interpolate(float a, float b, float x) { } }, ELASTIC_INOUT("elastic_inout") { + @Override public float interpolate(float a, float b, float x) { final float c5 = (2 * (float) Math.PI) / 4.5F; float v = (float) Math.sin((20 * x - 11.125) * c5); float factor = x == 0 ? 0 : (x == 1 ? 1 : - (x < 0.5 ? -((float) Math.pow(2, 20 * x - 10) * v) / 2 : - ((float) Math.pow(2, -20 * x + 10) * v) / 2 + 1)); + (x < 0.5 ? -((float) Math.pow(2, 20 * x - 10) * v) / 2 : + ((float) Math.pow(2, -20 * x + 10) * v) / 2 + 1)); return Interpolations.lerp(a, b, factor); } }, BOUNCE_IN("bounce_in") { + @Override public float interpolate(float a, float b, float x) { return Interpolations.lerp(a, b, 1 - BOUNCE_OUT.interpolate(0, 1, 1 - x)); } }, BOUNCE_OUT("bounce_out") { + @Override public float interpolate(float a, float b, float x) { final float n1 = 7.5625F; @@ -187,6 +205,7 @@ public float interpolate(float a, float b, float x) { } }, BOUNCE_INOUT("bounce_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = x < 0.5 ? (1 - BOUNCE_OUT.interpolate(0, 1, 1 - 2 * x)) / 2 : @@ -196,6 +215,7 @@ public float interpolate(float a, float b, float x) { } }, SINE_IN("sine_in") { + @Override public float interpolate(float a, float b, float x) { float factor = 1 - (float) Math.cos((x * Math.PI) / 2); @@ -204,6 +224,7 @@ public float interpolate(float a, float b, float x) { } }, SINE_OUT("sine_out") { + @Override public float interpolate(float a, float b, float x) { float factor = (float) Math.sin((x * Math.PI) / 2); @@ -212,6 +233,7 @@ public float interpolate(float a, float b, float x) { } }, SINE_INOUT("sine_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = (float) (-(Math.cos(Math.PI * x) - 1) / 2); @@ -220,6 +242,7 @@ public float interpolate(float a, float b, float x) { } }, QUART_IN("quart_in") { + @Override public float interpolate(float a, float b, float x) { float factor = x * x * x * x; @@ -228,6 +251,7 @@ public float interpolate(float a, float b, float x) { } }, QUART_OUT("quart_out") { + @Override public float interpolate(float a, float b, float x) { float factor = 1 - (float) Math.pow(1 - x, 4); @@ -236,6 +260,7 @@ public float interpolate(float a, float b, float x) { } }, QUART_INOUT("quart_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = x < 0.5 ? 8 * x * x * x * x : 1 - (float) Math.pow(-2 * x + 2, 4) / 2; @@ -244,6 +269,7 @@ public float interpolate(float a, float b, float x) { } }, QUINT_IN("quint_in") { + @Override public float interpolate(float a, float b, float x) { float factor = x * x * x * x * x; @@ -252,6 +278,7 @@ public float interpolate(float a, float b, float x) { } }, QUINT_OUT("quint_out") { + @Override public float interpolate(float a, float b, float x) { float factor = 1 - (float) Math.pow(1 - x, 5); @@ -260,6 +287,7 @@ public float interpolate(float a, float b, float x) { } }, QUINT_INOUT("quint_inout") { + @Override public float interpolate(float a, float b, float x) { float factor = x < 0.5 ? 16 * x * x * x * x * x : 1 - (float) Math.pow(-2 * x + 2, 5) / 2; @@ -268,6 +296,7 @@ public float interpolate(float a, float b, float x) { } }, CIRCLE_IN("circle_in") { + @Override public float interpolate(float a, float b, float x) { x = Mth.clamp(x, 0, 1); @@ -278,6 +307,7 @@ public float interpolate(float a, float b, float x) { } }, CIRCLE_OUT("circle_out") { + @Override public float interpolate(float a, float b, float x) { x = Mth.clamp(x, 0, 1); @@ -288,6 +318,7 @@ public float interpolate(float a, float b, float x) { } }, CIRCLE_INOUT("circle_inout") { + @Override public float interpolate(float a, float b, float x) { x = Mth.clamp(x, 0, 1); diff --git a/src/main/java/brachy/modularui/utils/MUIRenderTypes.java b/src/main/java/brachy/modularui/utils/MUIRenderTypes.java index a3b374e2..3530bf4a 100644 --- a/src/main/java/brachy/modularui/utils/MUIRenderTypes.java +++ b/src/main/java/brachy/modularui/utils/MUIRenderTypes.java @@ -4,11 +4,12 @@ import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; + import java.util.function.Function; @OnlyIn(Dist.CLIENT) @@ -50,7 +51,6 @@ public class MUIRenderTypes extends RenderType { .setWriteMaskState(RenderStateShard.COLOR_WRITE) .createCompositeState(false)); - private MUIRenderTypes(String name, VertexFormat format, VertexFormat.Mode mode, int bufferSize, boolean affectsCrumbling, boolean sortOnUpload, Runnable setupState, Runnable clearState) { super(name, format, mode, bufferSize, affectsCrumbling, sortOnUpload, setupState, clearState); diff --git a/src/main/java/brachy/modularui/utils/MatrixUtils.java b/src/main/java/brachy/modularui/utils/MatrixUtils.java index 77f73a07..8e93488c 100644 --- a/src/main/java/brachy/modularui/utils/MatrixUtils.java +++ b/src/main/java/brachy/modularui/utils/MatrixUtils.java @@ -1,20 +1,21 @@ package brachy.modularui.utils; import brachy.modularui.utils.math.MathUtils; + import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.core.Direction; import net.minecraft.util.Mth; -import com.mojang.blaze3d.platform.GlUtil; -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Table; import com.google.common.collect.Tables; +import com.mojang.blaze3d.platform.GlUtil; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; import org.jetbrains.annotations.Contract; import org.joml.Matrix4f; import org.joml.Matrix4fc; @@ -26,6 +27,7 @@ import java.nio.ByteBuffer; import java.security.InvalidParameterException; import java.util.Objects; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @@ -43,7 +45,7 @@ public class MatrixUtils { .synchronizedTable(HashBasedTable.create()); private static final ByteBuffer PIXEL_DEPTH_BUFFER = GlUtil.allocateMemory(4); - private static final int[] VIEWPORT_COORDS = {0, 0, 0, 0}; + private static final int[] VIEWPORT_COORDS = { 0, 0, 0, 0 }; /** * @param from the original vector @@ -284,13 +286,13 @@ public static Vector3f projectScreenToWorld(int x, int y, int viewWidth, int vie * This is in essence the same code as in gluProject, but it returns the resulting transformation matrixinstead of * applying it to the deprecated OpenGL transformation stack. * - * @param x X-coordinate in pixels - * @param y Y-coordinate in pixels - * @param viewport the viewport described by {@code [x, y, width, height]} + * @param x X-coordinate in pixels + * @param y Y-coordinate in pixels + * @param viewport the viewport described by {@code [x, y, width, height]} * @return world pos */ public static Vector3f projectScreenToWorld(int x, int y, int[] viewport) { - return projectScreenToWorld(x, y, viewport, 0, true); + return projectScreenToWorld(x, y, viewport, 0, true); } public static Vector3f projectScreenToWorld(int x, int y, int[] viewport, float depth) { diff --git a/src/main/java/brachy/modularui/utils/MouseData.java b/src/main/java/brachy/modularui/utils/MouseData.java index 2e0fac57..4629e084 100755 --- a/src/main/java/brachy/modularui/utils/MouseData.java +++ b/src/main/java/brachy/modularui/utils/MouseData.java @@ -3,10 +3,10 @@ import brachy.modularui.api.widget.Interactable; import net.minecraft.network.VarInt; -import com.mojang.blaze3d.platform.InputConstants; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.blaze3d.platform.InputConstants; import io.netty.buffer.ByteBuf; public record MouseData(Dist side, int mouseButton, boolean shift, boolean ctrl, boolean alt) { diff --git a/src/main/java/brachy/modularui/utils/NetworkUtils.java b/src/main/java/brachy/modularui/utils/NetworkUtils.java index 38c14e10..d52f0146 100644 --- a/src/main/java/brachy/modularui/utils/NetworkUtils.java +++ b/src/main/java/brachy/modularui/utils/NetworkUtils.java @@ -80,7 +80,6 @@ public static void writeStringSafe(ByteBuf buffer, @Nullable String string, int } public static String readStringSafe(ByteBuf buffer) { - int length = VarInt.read(buffer); if (length > MAX_ENCODED) { return null; diff --git a/src/main/java/brachy/modularui/utils/Rectangle.java b/src/main/java/brachy/modularui/utils/Rectangle.java index afe6ed17..d0f46c1f 100755 --- a/src/main/java/brachy/modularui/utils/Rectangle.java +++ b/src/main/java/brachy/modularui/utils/Rectangle.java @@ -325,7 +325,8 @@ public void set(int x, int y, int w, int h) { } public void subArea(float u0, float v0, float u1, float v1) { - set((int) (this.x + u0 * this.width), (int) (this.y + v0 * this.height), (int) ((u1 - u0) * this.width), (int) ((v1 - v0) * this.height)); + set((int) (this.x + u0 * this.width), (int) (this.y + v0 * this.height), (int) ((u1 - u0) * this.width), + (int) ((v1 - v0) * this.height)); } public PointF getCenter() { diff --git a/src/main/java/brachy/modularui/utils/RegistryAccessContainer.java b/src/main/java/brachy/modularui/utils/RegistryAccessContainer.java index e8b85d19..35efb9e3 100644 --- a/src/main/java/brachy/modularui/utils/RegistryAccessContainer.java +++ b/src/main/java/brachy/modularui/utils/RegistryAccessContainer.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Stream; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault diff --git a/src/main/java/brachy/modularui/utils/Stencil.java b/src/main/java/brachy/modularui/utils/Stencil.java index 3faa087e..8a2bc42b 100755 --- a/src/main/java/brachy/modularui/utils/Stencil.java +++ b/src/main/java/brachy/modularui/utils/Stencil.java @@ -8,13 +8,13 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ShaderInstance; + import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; - import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/brachy/modularui/utils/TooltipLines.java b/src/main/java/brachy/modularui/utils/TooltipLines.java index add6defe..236cdcfa 100755 --- a/src/main/java/brachy/modularui/utils/TooltipLines.java +++ b/src/main/java/brachy/modularui/utils/TooltipLines.java @@ -12,6 +12,7 @@ import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; import net.minecraft.world.inventory.tooltip.TooltipComponent; + import com.mojang.datafixers.util.Either; import java.util.AbstractList; diff --git a/src/main/java/brachy/modularui/utils/TreeUtil.java b/src/main/java/brachy/modularui/utils/TreeUtil.java index 31073a1b..ea2fd9af 100644 --- a/src/main/java/brachy/modularui/utils/TreeUtil.java +++ b/src/main/java/brachy/modularui/utils/TreeUtil.java @@ -87,7 +87,8 @@ public static > boolean foreachChildBFS(T parent, Predica * @param includeSelf true if the consumer should also consume the parent * @return true if the iteration was not terminated by the consumer */ - public static > boolean foreachChildBFS(T parent, Predicate consumer, boolean includeSelf) { + public static > boolean foreachChildBFS(T parent, Predicate consumer, + boolean includeSelf) { if (includeSelf && !consumer.test(parent)) return false; return parent.visitAllChildrenBFS(consumer); } @@ -127,7 +128,8 @@ public static > boolean foreachChild(T parent, Predicate< * @param includeSelf true if the consumer should also consume the parent * @return the first resulting value of the consumer or null of it always returned null */ - public static , V> @Nullable V foreachChildWithResult(T parent, Function consumer, boolean includeSelf) { + public static , V> @Nullable V foreachChildWithResult(T parent, Function consumer, + boolean includeSelf) { if (includeSelf) { V t = consumer.apply(parent); if (t != null) return t; @@ -333,7 +335,8 @@ public static , R extends ITreeNode> R findParent(T pa @Nullable @SuppressWarnings("unchecked") - public static , R extends ITreeNode> R findParent(T parent, Class type, @Nullable Predicate test) { + public static , R extends ITreeNode> R findParent(T parent, Class type, + @Nullable Predicate test) { while (parent != null) { if (type.isAssignableFrom(parent.getClass()) && (test == null || test.test((R) parent))) { return (R) parent; diff --git a/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java b/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java index e17a02f7..dad3d1b1 100644 --- a/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java +++ b/src/main/java/brachy/modularui/utils/handlers/fluid/CycleFluidEntryHandler.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault diff --git a/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java b/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java index 4ae0cf17..15feb911 100644 --- a/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java +++ b/src/main/java/brachy/modularui/utils/handlers/item/CycleItemEntryHandler.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; + import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault diff --git a/src/main/java/brachy/modularui/utils/math/DAM.java b/src/main/java/brachy/modularui/utils/math/DAM.java index 0c24d278..3be5fd42 100644 --- a/src/main/java/brachy/modularui/utils/math/DAM.java +++ b/src/main/java/brachy/modularui/utils/math/DAM.java @@ -274,7 +274,7 @@ public static double[] pow(double[] src, double op, double @Nullable [] res) { public static double[] diff(double[] src) { if (src.length < 2) return EMPTY; - if (src.length == 2) return new double[]{src[1] - src[0]}; + if (src.length == 2) return new double[] { src[1] - src[0] }; double[] res = new double[src.length - 1]; for (int i = 0; i < res.length; i++) { res[i] = src[i + 1] - src[i]; diff --git a/src/main/java/brachy/modularui/utils/math/FAM.java b/src/main/java/brachy/modularui/utils/math/FAM.java index c62ef89b..c98f0355 100644 --- a/src/main/java/brachy/modularui/utils/math/FAM.java +++ b/src/main/java/brachy/modularui/utils/math/FAM.java @@ -215,7 +215,7 @@ public static float[] div(float[] src, float[] op, float @Nullable [] res) { public static float[] diff(float[] src) { if (src.length < 2) return EMPTY; - if (src.length == 2) return new float[]{src[1] - src[0]}; + if (src.length == 2) return new float[] { src[1] - src[0] }; float[] res = new float[src.length - 1]; for (int i = 0; i < res.length; i++) { res[i] = src[i + 1] - src[i]; diff --git a/src/main/java/brachy/modularui/utils/math/MathUtils.java b/src/main/java/brachy/modularui/utils/math/MathUtils.java index 9d5383b8..6a48c0eb 100644 --- a/src/main/java/brachy/modularui/utils/math/MathUtils.java +++ b/src/main/java/brachy/modularui/utils/math/MathUtils.java @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; + import javax.annotation.ParametersAreNonnullByDefault; @MethodsReturnNonnullByDefault @@ -154,7 +155,7 @@ public static int gridRows(int count, int size, int width) { return count <= 0 ? 1 : (int) Math.ceil(x); } - public static int min(int @Nullable ... values) { + public static int min(int @Nullable... values) { if (values == null || values.length == 0) throw new IllegalArgumentException(); if (values.length == 1) return values[0]; if (values.length == 2) return Math.min(values[0], values[1]); @@ -167,7 +168,7 @@ public static int min(int @Nullable ... values) { return min; } - public static int max(int @Nullable ... values) { + public static int max(int @Nullable... values) { if (values == null || values.length == 0) throw new IllegalArgumentException(); if (values.length == 1) return values[0]; if (values.length == 2) return Math.max(values[0], values[1]); diff --git a/src/main/java/brachy/modularui/utils/math/NumberFormat.java b/src/main/java/brachy/modularui/utils/math/NumberFormat.java index 3b46cfe3..106a83c2 100644 --- a/src/main/java/brachy/modularui/utils/math/NumberFormat.java +++ b/src/main/java/brachy/modularui/utils/math/NumberFormat.java @@ -35,9 +35,11 @@ public class NumberFormat { .build(); public static Params params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, - boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, boolean considerSuffixForLength, + boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, + boolean considerSuffixForLength, boolean spaceAfterNumber) { - return new Params(format, maxLength, considerOnlyDecimalsForLength, considerDecimalSeparatorForLength, considerMinusForLength, considerSuffixForLength, spaceAfterNumber); + return new Params(format, maxLength, considerOnlyDecimalsForLength, considerDecimalSeparatorForLength, + considerMinusForLength, considerSuffixForLength, spaceAfterNumber); } public static ParamsBuilder paramsBuilder() { @@ -45,50 +47,52 @@ public static ParamsBuilder paramsBuilder() { } public record Params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, - boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, boolean considerSuffixForLength, + boolean considerDecimalSeparatorForLength, boolean considerMinusForLength, + boolean considerSuffixForLength, boolean spaceAfterNumber) { - public Params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, boolean considerDecimalSeparatorForLength, - boolean considerMinusForLength, boolean considerSuffixForLength, boolean spaceAfterNumber) { - this.format = format; - this.maxLength = maxLength; - this.considerOnlyDecimalsForLength = considerOnlyDecimalsForLength; - this.considerDecimalSeparatorForLength = considerDecimalSeparatorForLength; - this.considerMinusForLength = considerMinusForLength; - this.considerSuffixForLength = considerSuffixForLength; - this.spaceAfterNumber = spaceAfterNumber; - if (!this.considerOnlyDecimalsForLength && this.maxLength < 1) { - throw new IllegalArgumentException("Max length must be at least 1 character"); - } + public Params(DecimalFormat format, int maxLength, boolean considerOnlyDecimalsForLength, + boolean considerDecimalSeparatorForLength, + boolean considerMinusForLength, boolean considerSuffixForLength, boolean spaceAfterNumber) { + this.format = format; + this.maxLength = maxLength; + this.considerOnlyDecimalsForLength = considerOnlyDecimalsForLength; + this.considerDecimalSeparatorForLength = considerDecimalSeparatorForLength; + this.considerMinusForLength = considerMinusForLength; + this.considerSuffixForLength = considerSuffixForLength; + this.spaceAfterNumber = spaceAfterNumber; + if (!this.considerOnlyDecimalsForLength && this.maxLength < 1) { + throw new IllegalArgumentException("Max length must be at least 1 character"); } + } - public ParamsBuilder copyToBuilder() { - DecimalFormat format = (DecimalFormat) this.format.clone(); - format.setMinimumFractionDigits(this.format.getMinimumFractionDigits()); - format.setMaximumFractionDigits(this.format.getMaximumFractionDigits()); - format.setMinimumIntegerDigits(this.format.getMinimumIntegerDigits()); - format.setMaximumIntegerDigits(this.format.getMaximumIntegerDigits()); - format.setRoundingMode(this.format.getRoundingMode()); - format.setGroupingSize(this.format.getGroupingSize()); - format.setGroupingUsed(this.format.isGroupingUsed()); - return new ParamsBuilder() - .format(format) - .maxLength(this.maxLength) - .considerOnlyDecimalsForLength(this.considerOnlyDecimalsForLength) - .considerDecimalSeparatorForLength(this.considerDecimalSeparatorForLength) - .considerMinusForLength(this.considerMinusForLength) - .considerSuffixForLength(this.considerSuffixForLength) - .spaceAfterNumber(this.spaceAfterNumber); - } + public ParamsBuilder copyToBuilder() { + DecimalFormat format = (DecimalFormat) this.format.clone(); + format.setMinimumFractionDigits(this.format.getMinimumFractionDigits()); + format.setMaximumFractionDigits(this.format.getMaximumFractionDigits()); + format.setMinimumIntegerDigits(this.format.getMinimumIntegerDigits()); + format.setMaximumIntegerDigits(this.format.getMaximumIntegerDigits()); + format.setRoundingMode(this.format.getRoundingMode()); + format.setGroupingSize(this.format.getGroupingSize()); + format.setGroupingUsed(this.format.isGroupingUsed()); + return new ParamsBuilder() + .format(format) + .maxLength(this.maxLength) + .considerOnlyDecimalsForLength(this.considerOnlyDecimalsForLength) + .considerDecimalSeparatorForLength(this.considerDecimalSeparatorForLength) + .considerMinusForLength(this.considerMinusForLength) + .considerSuffixForLength(this.considerSuffixForLength) + .spaceAfterNumber(this.spaceAfterNumber); + } - public String format(double number) { - return NumberFormat.format(number, this); - } + public String format(double number) { + return NumberFormat.format(number, this); + } - public String format(BigDecimal number) { - return NumberFormat.format(number, this); - } + public String format(BigDecimal number) { + return NumberFormat.format(number, this); } + } public static class ParamsBuilder { @@ -160,7 +164,8 @@ public ParamsBuilder spaceAfterNumber(boolean spaceAfterNumber) { } public Params build() { - return new Params(checkFormat(), this.maxLength, this.considerOnlyDecimalsForLength, this.considerDecimalSeparatorForLength, + return new Params(checkFormat(), this.maxLength, this.considerOnlyDecimalsForLength, + this.considerDecimalSeparatorForLength, this.considerMinusForLength, this.considerSuffixForLength, spaceAfterNumber); } } @@ -224,7 +229,8 @@ public static SIPrefix findBestPrefix(double number) { public static SIPrefix findBestPrefix(BigDecimal number) { number = number.abs(); - if ((number.compareTo(BigDecimal.ONE) >= 0 && number.compareTo(TEN_THOUSAND) < 0) || number.equals(BigDecimal.ZERO)) { + if ((number.compareTo(BigDecimal.ONE) >= 0 && number.compareTo(TEN_THOUSAND) < 0) || + number.equals(BigDecimal.ZERO)) { return SIPrefix.One; } SIPrefix[] high = SIPrefix.HIGH; diff --git a/src/main/java/brachy/modularui/utils/math/ParseResult.java b/src/main/java/brachy/modularui/utils/math/ParseResult.java index e72c5c32..c32b530a 100644 --- a/src/main/java/brachy/modularui/utils/math/ParseResult.java +++ b/src/main/java/brachy/modularui/utils/math/ParseResult.java @@ -50,6 +50,7 @@ public String getErrorMessage() { return isFailure() ? String.format("%s for Token %s at %d:%d", this.error.getMessage(), this.error.getTokenString(), - this.error.getStartPosition(), this.error.getEndPosition()) : null; + this.error.getStartPosition(), this.error.getEndPosition()) : + null; } } diff --git a/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java b/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java index db3cd4be..9d111e64 100644 --- a/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java +++ b/src/main/java/brachy/modularui/utils/math/PostfixPercentOperator.java @@ -16,7 +16,8 @@ public class PostfixPercentOperator extends AbstractOperator { public static final BigDecimal HUNDRED = new BigDecimal(100); @Override - public EvaluationValue evaluate(Expression expression, Token operatorToken, EvaluationValue... operands) throws EvaluationException { + public EvaluationValue evaluate(Expression expression, Token operatorToken, + EvaluationValue... operands) throws EvaluationException { EvaluationValue operand = operands[0]; if (operand.isNumberValue()) { diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java b/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java index be0b938c..3a51d597 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/CodecRegistry.java @@ -2,7 +2,6 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; - import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java b/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java index 1aa72530..de55e95c 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/CodecUtil.java @@ -11,7 +11,6 @@ import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; import com.mojang.serialization.codecs.KeyDispatchCodec; - import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import java.util.ArrayList; @@ -56,6 +55,7 @@ public static Codec nullCodec(Supplier decoder) { public static Codec nullCodec(Supplier decoder, Predicate nullTester) { return new Codec<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { if (input == null || Objects.equals(ops.empty(), input)) { @@ -92,6 +92,7 @@ public static Decoder chainedDecoder(Decoder... decoder) { if (decoder == null || decoder.length == 0) throw new NullPointerException(); if (decoder.length == 1) return decoder[0]; return new Decoder<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { StringBuilder message = new StringBuilder(); @@ -111,6 +112,7 @@ public static Encoder chainedEncoder(Encoder... encoder) { if (encoder == null || encoder.length == 0) throw new NullPointerException(); if (encoder.length == 1) return encoder[0]; return new Encoder<>() { + @Override public DataResult encode(A input, DynamicOps ops, T prefix) { StringBuilder message = new StringBuilder(); @@ -131,6 +133,7 @@ public static MapCodec chainedMapCodec(MapCodec... codecs) { if (codecs.length == 1) return codecs[0]; // I hate this return new MapCodec<>() { + @Override public Stream keys(DynamicOps ops) { Stream s = Stream.empty(); @@ -174,13 +177,15 @@ public static Decoder optionsDecoder(Decoder... codecs) { if (codecs == null || codecs.length == 0) throw new NullPointerException(); if (codecs.length == 1) return (Codec) codecs[0]; return new Decoder<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { StringBuilder message = new StringBuilder(); for (var codec : codecs) { var d = codec.decode(ops, input); var res = d.result(); - if (res.isPresent()) return DataResult.success(new Pair<>(res.get().getFirst(), res.get().getSecond())); + if (res.isPresent()) + return DataResult.success(new Pair<>(res.get().getFirst(), res.get().getSecond())); message.append(d.error().orElseThrow().message()).append("; "); } return DataResult.error(() -> message.substring(0, message.length() - 2)); @@ -200,8 +205,8 @@ public static Codec codecOf(Encoder encoder, Decoder... decoder) { return Codec.of(encoder, chainedDecoder(decoder)); } - public static MapCodec dispatchNullable(Codec keyCodec, Function type, Function> codec) { + public static MapCodec dispatchNullable(Codec keyCodec, Function type, + Function> codec) { return dispatchNullable("type", keyCodec, type, codec); } @@ -225,20 +230,22 @@ public static MapCodec partialDispatchMap(String key, Codec keyCode Function> type, Function>> codec) { return new KeyDispatchCodec<>(key, keyCodec, type, codec); - } public static Encoder checked(Encoder codec, Predicate test) { return new Encoder<>() { + @Override public DataResult encode(A input, DynamicOps ops, T prefix) { - return test.test(input) ? codec.encode(input, ops, prefix) : DataResult.error(() -> "Codec " + codec + " can't handle value " + input); + return test.test(input) ? codec.encode(input, ops, prefix) : + DataResult.error(() -> "Codec " + codec + " can't handle value " + input); } }; } public static Codec checkedEncoder(Codec codec, Predicate test) { return new Codec<>() { + @Override public DataResult> decode(DynamicOps ops, T input) { return codec.decode(ops, input); @@ -246,7 +253,8 @@ public DataResult> decode(DynamicOps ops, T input) { @Override public DataResult encode(A input, DynamicOps ops, T prefix) { - return test.test(input) ? codec.encode(input, ops, prefix) : DataResult.error(() -> "Codec " + codec + " can't handle value " + input); + return test.test(input) ? codec.encode(input, ops, prefix) : + DataResult.error(() -> "Codec " + codec + " can't handle value " + input); } @Override diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/Field.java b/src/main/java/brachy/modularui/utils/serialization/codec/Field.java index 9885cebf..8ee93a2b 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/Field.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/Field.java @@ -6,7 +6,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; - import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -19,12 +18,18 @@ @Accessors(fluent = true, chain = true) public final class Field { - @Getter private final String name; - @Getter private final FieldWriter fieldWriter; - @Getter private final FieldReader fieldReader; - @Getter private final Codec codec; - @Getter private final Supplier defaultSupplier; - @Getter private final boolean dynamicSupplier; + @Getter + private final String name; + @Getter + private final FieldWriter fieldWriter; + @Getter + private final FieldReader fieldReader; + @Getter + private final Codec codec; + @Getter + private final Supplier defaultSupplier; + @Getter + private final boolean dynamicSupplier; @Getter @Setter private String[] altNames; @@ -35,7 +40,8 @@ public final class Field { @Setter private boolean writeDefault = true; - Field(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec, Supplier defaultSupplier, boolean dynamicSupplier) { + Field(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec, + Supplier defaultSupplier, boolean dynamicSupplier) { this.name = name; this.fieldWriter = fieldWriter; this.fieldReader = fieldReader; @@ -70,13 +76,15 @@ public void encode(T holder, DynamicOps ops, RecordBuilder map) { V value = this.fieldReader.readField(holder); if (isUnencodable()) { if (!isEmpty(value)) { - map.withErrorsFrom(DataResult.error(() -> String.format("Field '%s' is unencodeable, but the value is not empty", this.name))); + map.withErrorsFrom(DataResult.error( + () -> String.format("Field '%s' is unencodeable, but the value is not empty", this.name))); } return; } if (value == null) { if (!hasDefault()) { - map.withErrorsFrom(DataResult.error(() -> String.format("Field '%s' is not optional, but is trying to encode a null value", this.name))); + map.withErrorsFrom(DataResult.error(() -> String + .format("Field '%s' is not optional, but is trying to encode a null value", this.name))); return; } if (this.encodeWhen == EncodeWhen.ALWAYS) { @@ -108,7 +116,8 @@ public boolean shouldEncode(V value) { if (element == null) { if (this.encodeWhen == EncodeWhen.NEVER || !this.writeDefault) return null; if (!hasDefault()) { - return null;//isUnencodable() ? null : String.format("Field '%s' has no value and is not optional", this.name); + return null;// isUnencodable() ? null : String.format("Field '%s' has no value and is not optional", + // this.name); } this.fieldWriter.writeField(holder, getModifiableDefault()); return null; @@ -153,7 +162,9 @@ private DataResult decode(T holder, DynamicOps ops, J element, Mutable value = res.get(); } if (value == null) { - return DataResult.error(() -> String.format("Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", this.name)); + return DataResult.error(() -> String.format( + "Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", + this.name)); } } return decoder.decode(ops, dRes.get(), value); @@ -172,7 +183,9 @@ private DataResult decode(T holder, DynamicOps ops, J element, Mutable value = res.get(); } if (value == null) { - return DataResult.error(() -> String.format("Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", this.name)); + return DataResult.error(() -> String.format( + "Field '%s' is unable to decode instance and the holder has no default value and this property has no default value", + this.name)); } } return decoder.parse(ops, element, value); @@ -202,7 +215,8 @@ public Field copyToType(Function converter) { public Field copyToType(String newName, Function converter) { var field = new Field(newName, (o, v) -> this.fieldWriter.writeField(converter.apply(o), v), - (o) -> this.fieldReader.readField(converter.apply(o)), this.codec, this.defaultSupplier, this.dynamicSupplier); + (o) -> this.fieldReader.readField(converter.apply(o)), this.codec, this.defaultSupplier, + this.dynamicSupplier); field.altNames(this.altNames); field.encodeWhen(this.encodeWhen); field.writeDefault(this.writeDefault); @@ -211,7 +225,8 @@ public Field copyToType(String newName, Function converter) { public Field copy(String newName) { if (this.name.equals(newName)) return this; - var field = new Field<>(newName, this.fieldWriter, this.fieldReader, this.codec, this.defaultSupplier, this.dynamicSupplier); + var field = new Field<>(newName, this.fieldWriter, this.fieldReader, this.codec, this.defaultSupplier, + this.dynamicSupplier); field.altNames(this.altNames); field.encodeWhen(this.encodeWhen); field.writeDefault(this.writeDefault); @@ -222,7 +237,8 @@ public void convertToString(T instance, StringBuilder b, int indent) { b.append(this.name) .append(": "); V value = this.fieldReader.readField(instance); - if (this.codec instanceof MapCodec.MapCodecCodec(MapCodec mapCodec) && mapCodec instanceof MutableObjectCodec moc) { + if (this.codec instanceof MapCodec.MapCodecCodec(MapCodec mapCodec) && + mapCodec instanceof MutableObjectCodec moc) { b.append(moc.convertToString(value, indent)); } else { b.append(value); diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java b/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java index 94c04a1b..e31a2264 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/MutableCodec.java @@ -1,13 +1,12 @@ package brachy.modularui.utils.serialization.codec; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - /** * A {@link Codec} that can decode mutable field to an existing instance. * diff --git a/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java b/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java index e19fa3f7..7921a3eb 100644 --- a/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java +++ b/src/main/java/brachy/modularui/utils/serialization/codec/MutableObjectCodec.java @@ -3,6 +3,8 @@ import brachy.modularui.api.drawable.IDrawable; import brachy.modularui.api.widget.IWidget; +import com.google.common.base.CaseFormat; +import com.google.gson.JsonObject; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; @@ -10,9 +12,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; - -import com.google.common.base.CaseFormat; -import com.google.gson.JsonObject; import it.unimi.dsi.fastutil.objects.Object2ReferenceLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ReferenceMap; import lombok.Getter; @@ -32,7 +31,8 @@ import java.util.stream.Stream; /** - * This can handle (de)serialization and conversion to various data types, editing properties, copying properties and applying default + * This can handle (de)serialization and conversion to various data types, editing properties, copying properties and + * applying default * properties to (partially) mutable objects. * * @param type of property @@ -44,7 +44,8 @@ public class MutableObjectCodec extends MapCodec implements MutableMapDeco private final InstanceMapDecoder instanceDecoder; private final UnaryOperator baseCopy; private final Codec wrapped; - @Getter private final MutableCodecCodec mutableCodec = new MutableCodecCodec<>(this); + @Getter + private final MutableCodecCodec mutableCodec = new MutableCodecCodec<>(this); private MutableObjectCodec(List> fields, InstanceMapDecoder instanceDecoder, UnaryOperator baseCopy, Codec wrapped) { @@ -136,7 +137,8 @@ public static Builder drawableBuilder(Class type, St return new DrawableBuilder<>(typeName); } - public static Builder drawableBuilder(String typeName, InstanceMapDecoder instanceDecoder) { + public static Builder drawableBuilder(String typeName, + InstanceMapDecoder instanceDecoder) { return new DrawableBuilder(typeName).instanceDecoder(instanceDecoder); } @@ -144,7 +146,8 @@ public static Builder drawableBuilder(String typeName, return new DrawableBuilder(typeName).instance(instance); } - public static Builder drawableBuilder(Class type, InstanceMapDecoder instanceDecoder) { + public static Builder drawableBuilder(Class type, + InstanceMapDecoder instanceDecoder) { return new DrawableBuilder(type.getSimpleName()).instanceDecoder(instanceDecoder); } @@ -204,7 +207,8 @@ public DataResult decode(DynamicOps ops, MapLike input, T instance) if (error != null) errors.add(error); }); if (!errors.isEmpty()) { - return DataResult.error(() -> String.format("Errors while decoding object of type '%s': %s", instance.getClass().getSimpleName(), errors)); + return DataResult.error(() -> String.format("Errors while decoding object of type '%s': %s", + instance.getClass().getSimpleName(), errors)); } return DataResult.success(instance); } @@ -248,7 +252,8 @@ public DataResult decodeInstance(DynamicOps ops, MapLike input) { return this.wrapped.parse(ops, ops.createMap(input.entries())); } if (this.instanceDecoder != null) return this.instanceDecoder.decodeInstance(ops, input); - return DataResult.error(() -> "Instance can not be created since no instance decoder or wrapped codec was provided."); + return DataResult + .error(() -> "Instance can not be created since no instance decoder or wrapped codec was provided."); } public String convertToString(T instance, boolean pretty) { @@ -281,12 +286,14 @@ public record MutableCodecCodec(MutableObjectCodec codec) implements Mutab @Override public DataResult> decode(DynamicOps ops, T input, A instance) { - return CodecUtil.ifMap(ops, input, map -> this.codec.decode(ops, map, instance)).map(t -> new Pair<>(t, input)); + return CodecUtil.ifMap(ops, input, map -> this.codec.decode(ops, map, instance)) + .map(t -> new Pair<>(t, input)); } @Override public DataResult> decodeInstance(DynamicOps ops, T input) { - return CodecUtil.ifMap(ops, input, map -> this.codec.decodeInstance(ops, map)).map(t -> new Pair<>(t, input)); + return CodecUtil.ifMap(ops, input, map -> this.codec.decodeInstance(ops, map)) + .map(t -> new Pair<>(t, input)); } @Override @@ -309,7 +316,8 @@ public static class Builder { /** * Sets the instance decoder. This is needed when parsing from JSON. The decoder should create a new instance - * and decode any necessary data for that. If the object has a no-arg constructor, then {@link #instance(Supplier)} should be used. + * and decode any necessary data for that. If the object has a no-arg constructor, then + * {@link #instance(Supplier)} should be used. * If this setter is used, then {@link #baseCopy(UnaryOperator)} must also be used. */ public Builder instanceDecoder(InstanceMapDecoder instanceDecoder) { @@ -318,10 +326,12 @@ public Builder instanceDecoder(InstanceMapDecoder instanceDecoder) { } /** - * Sets the instance supplier. This is needed when parsing from JSON and for copying. This MUST always return a new instance. + * Sets the instance supplier. This is needed when parsing from JSON and for copying. This MUST always return a + * new instance. */ public Builder instance(Supplier instance) { return instanceDecoder(new InstanceMapDecoder() { + @Override public DataResult decodeInstance(DynamicOps ops, MapLike input) { return DataResult.success(instance.get()); @@ -330,7 +340,8 @@ public DataResult decodeInstance(DynamicOps ops, MapLike input) { } /** - * Sets the base copy function. This creates a new instance, but without setting any mutable properties. This MUST always return + * Sets the base copy function. This creates a new instance, but without setting any mutable properties. This + * MUST always return * a new instance. If the object has a no-arg constructor, then {@link #instance(Supplier)} should be used. */ public Builder baseCopy(UnaryOperator baseCopy) { @@ -343,7 +354,8 @@ public Builder baseCopy(UnaryOperator baseCopy) { } /** - * When this object is encoded and decoded this codec will be called first. This is useful when this object is based on another + * When this object is encoded and decoded this codec will be called first. This is useful when this object is + * based on another * object which already has a codec. * *

@@ -399,14 +411,16 @@ public

Builder addFieldOf(MutableObjectCodec

parent, Function co return addFieldOf(parent, converter, fieldName, fieldName); } - public

Builder addFieldOf(MutableObjectCodec

parent, Function converter, String fieldName, String newName) { + public

Builder addFieldOf(MutableObjectCodec

parent, Function converter, String fieldName, + String newName) { parent.findField(fieldName).ifPresentOrElse(f -> addField(f.copyToType(newName, converter)), () -> { throw new IllegalArgumentException("MutableObjectCodec does not have field '" + fieldName + "'."); }); return this; } - public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, MapCodec codec) { + public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, + MapCodec codec) { return addDynOpt(name, fieldWriter, fieldReader, codec.codec(), null); } @@ -415,7 +429,8 @@ public Builder add(String name, FieldWriter fieldWriter, FieldReade * * @see #addDynOpt(String, FieldWriter, FieldReader, Codec, Supplier) */ - public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec) { + public Builder add(String name, FieldWriter fieldWriter, FieldReader fieldReader, + Codec codec) { return addDynOpt(name, fieldWriter, fieldReader, codec, null); } @@ -427,7 +442,8 @@ public Builder addOpt(String name, FieldWriter fieldWriter, FieldRe /** * Adds a new optional, mutable property with a const default value. * - * @param defValue default value, if this is null, the default value is null and this property is still considered optional + * @param defValue default value, if this is null, the default value is null and this property is still + * considered optional * @see #addDynOpt(String, FieldWriter, FieldReader, Codec, Supplier) */ public Builder addOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, @@ -438,7 +454,8 @@ public Builder addOpt(String name, FieldWriter fieldWriter, FieldRe return addField(new Field<>(name, fieldWriter, fieldReader, codec, () -> defValue, false)); } - public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, MapCodec codec, + public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + MapCodec codec, @Nullable Supplier defaultSupplier) { return addDynOpt(name, fieldWriter, fieldReader, codec.codec(), defaultSupplier); } @@ -455,7 +472,8 @@ public Builder addDynOpt(String name, FieldWriter fieldWriter, Fiel * @return this * @throws NullPointerException if name, fieldEncoder or fieldDecoder is null */ - public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, Codec codec, + public Builder addDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + Codec codec, @Nullable Supplier defaultSupplier) { Objects.requireNonNull(name, "Name of field must not be null!"); Objects.requireNonNull(fieldWriter, "Field encoder must not be null!"); @@ -464,11 +482,13 @@ public Builder addDynOpt(String name, FieldWriter fieldWriter, Fiel .encodeWhen(Field.EncodeWhen.ALWAYS)); } - public Builder addUnencodable(String name, FieldWriter fieldWriter, FieldReader fieldReader) { + public Builder addUnencodable(String name, FieldWriter fieldWriter, + FieldReader fieldReader) { return add(name, fieldWriter, fieldReader, (Codec) null); } - public Builder addUnencodableOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + public Builder addUnencodableOpt(String name, FieldWriter fieldWriter, + FieldReader fieldReader, @Nullable V defaultValue) { return addOpt(name, fieldWriter, fieldReader, (Codec) null, defaultValue); } @@ -480,7 +500,8 @@ public Builder addUnencodableOpt(String name, FieldWriter fieldWrit * * @see #addDynOpt(String, FieldWriter, FieldReader, Codec, Supplier) */ - public Builder addUnencodableDynOpt(String name, FieldWriter fieldWriter, FieldReader fieldReader, + public Builder addUnencodableDynOpt(String name, FieldWriter fieldWriter, + FieldReader fieldReader, @Nullable Supplier defaultSupplier) { return addDynOpt(name, fieldWriter, fieldReader, (Codec) null, defaultSupplier); } @@ -521,7 +542,8 @@ private Builder doOnField(Consumer> consumer) { } public MutableObjectCodec build() { - var c = new MutableObjectCodec<>(new ArrayList<>(this.fields.values()), this.instanceDecoder, this.baseCopy, this.wrapped); + var c = new MutableObjectCodec<>(new ArrayList<>(this.fields.values()), this.instanceDecoder, this.baseCopy, + this.wrapped); if (this.registry != null) { this.registry.register(c, this.names); } diff --git a/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java b/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java index 95da9a07..c41bc035 100755 --- a/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java +++ b/src/main/java/brachy/modularui/utils/serialization/json/JsonHelper.java @@ -3,16 +3,15 @@ import brachy.modularui.ModularUI; import brachy.modularui.utils.serialization.codec.MutableCodec; -import com.mojang.serialization.Decoder; -import com.mojang.serialization.Encoder; -import com.mojang.serialization.JsonOps; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.mojang.serialization.Decoder; +import com.mojang.serialization.Encoder; +import com.mojang.serialization.JsonOps; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -53,7 +52,7 @@ public static T deserializeWithFallback(JsonObject json, JsonObject fallback return t != null ? t : deserialize(fallback, clazz, defaultValue, keys); } - public static float getFloat(JsonObject json, float defaultValue, String @NotNull ... keys) { + public static float getFloat(JsonObject json, float defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -67,7 +66,7 @@ public static float getFloat(JsonObject json, float defaultValue, String @NotNul return defaultValue; } - public static int getInt(JsonObject json, int defaultValue, String @NotNull ... keys) { + public static int getInt(JsonObject json, int defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -82,12 +81,12 @@ public static int getInt(JsonObject json, int defaultValue, String @NotNull ... } public static int getIntWithFallback(JsonObject json, JsonObject fallback, int defaultValue, - String @NotNull ... keys) { + String @NotNull... keys) { Integer i = getBoxedInt(json, null, keys); return i != null ? i : getInt(fallback, defaultValue, keys); } - public static boolean getBoolean(JsonObject json, boolean defaultValue, String @NotNull ... keys) { + public static boolean getBoolean(JsonObject json, boolean defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -102,12 +101,12 @@ public static boolean getBoolean(JsonObject json, boolean defaultValue, String @ } public static boolean getBoolWithFallback(JsonObject json, JsonObject fallback, boolean defaultValue, - String @NotNull ... keys) { + String @NotNull... keys) { Boolean i = getBoxedBool(json, null, keys); return i != null ? i : getBoolean(fallback, defaultValue, keys); } - public static String getString(JsonObject json, String defaultValue, String @NotNull ... keys) { + public static String getString(JsonObject json, String defaultValue, String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -119,7 +118,7 @@ public static String getString(JsonObject json, String defaultValue, String @Not } public static T getObject(JsonObject json, T defaultValue, Function factory, - String @NotNull ... keys) { + String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -134,7 +133,7 @@ public static T getObject(JsonObject json, T defaultValue, Function T getElement(JsonObject json, T defaultValue, Function factory, - String @NotNull ... keys) { + String @NotNull... keys) { if (json == null) return defaultValue; for (String key : keys) { if (json.has(key)) { @@ -145,7 +144,7 @@ public static T getElement(JsonObject json, T defaultValue, Function T getElement(JsonObject json, T defaultValue, Function T getElement(JsonObject json, T defaultValue, Function IByteBufAdapter makeMemberAdapter(@NotNull StreamDeco return makeAdapter(decoder, (buffer, value) -> memberEncoder.encode(value, buffer), comparator); } - public static IByteBufAdapter makeAdapterFromCodec(@NotNull Codec codec, @NotNull EqualityTest equals) { + public static IByteBufAdapter makeAdapterFromCodec(@NotNull Codec codec, + @NotNull EqualityTest equals) { return new IByteBufAdapter<>() { private static final Gson GSON = new Gson(); @Override public V decode(B buffer) { - JsonElement jsonelement = GsonHelper.fromJson(GSON, Utf8String.read(buffer, FriendlyByteBuf.MAX_STRING_LENGTH), JsonElement.class); + JsonElement jsonelement = GsonHelper.fromJson(GSON, + Utf8String.read(buffer, FriendlyByteBuf.MAX_STRING_LENGTH), JsonElement.class); DataResult dataresult = codec.parse(JsonOps.COMPRESSED, jsonelement); return dataresult.getOrThrow(p_272382_ -> new DecoderException("Failed to decode json: " + p_272382_)); } @@ -193,7 +192,10 @@ public V decode(B buffer) { @Override public void encode(B buffer, V u) { DataResult dataresult = codec.encodeStart(JsonOps.COMPRESSED, u); - Utf8String.write(buffer, GSON.toJson(dataresult.getOrThrow(e -> new EncoderException("Failed to encode json: " + e + " " + u))), FriendlyByteBuf.MAX_STRING_LENGTH); + Utf8String.write(buffer, + GSON.toJson(dataresult + .getOrThrow(e -> new EncoderException("Failed to encode json: " + e + " " + u))), + FriendlyByteBuf.MAX_STRING_LENGTH); } @Override diff --git a/src/main/java/brachy/modularui/value/ProgressValue.java b/src/main/java/brachy/modularui/value/ProgressValue.java index cb9cdca3..27fee8d8 100644 --- a/src/main/java/brachy/modularui/value/ProgressValue.java +++ b/src/main/java/brachy/modularui/value/ProgressValue.java @@ -8,7 +8,8 @@ public class ProgressValue extends DoubleValue { - @Getter private final int duration; + @Getter + private final int duration; public ProgressValue(int duration) { super(0); diff --git a/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java b/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java index b2685deb..5762caa1 100644 --- a/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/AbstractGenericSyncValue.java @@ -10,7 +10,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public abstract class AbstractGenericSyncValue> extends ValueSyncHandler { +public abstract class AbstractGenericSyncValue> + extends ValueSyncHandler { private final Class type; private final Supplier getter; @@ -23,7 +24,8 @@ protected AbstractGenericSyncValue(Class type, Supplier getter, Consumer) this.cache.getClass(); } @@ -47,7 +49,8 @@ protected AbstractGenericSyncValue(Class type, @Nullable Supplier clientGe this.cache = this.getter.get(); if (type == null) { if (this.cache == null) { - throw new IllegalArgumentException("If the value class is not give, then the getter must return a non null value!"); + throw new IllegalArgumentException( + "If the value class is not give, then the getter must return a non null value!"); } type = (Class) this.cache.getClass(); } @@ -128,7 +131,8 @@ public boolean isValueOfType(Class expectedType) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -138,8 +142,10 @@ public void modifyValue(Consumer consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ diff --git a/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java b/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java index 39fdb0d8..7a01085d 100644 --- a/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/BooleanSyncValue.java @@ -14,7 +14,7 @@ import java.util.function.BooleanSupplier; public class BooleanSyncValue extends ValueSyncHandler - implements IBoolSyncValue, IStringSyncValue { + implements IBoolSyncValue, IStringSyncValue { private final BooleanSupplier getter; private final BooleanConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/ByteSyncValue.java b/src/main/java/brachy/modularui/value/sync/ByteSyncValue.java index c1121a0d..38463282 100644 --- a/src/main/java/brachy/modularui/value/sync/ByteSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/ByteSyncValue.java @@ -11,7 +11,8 @@ import java.util.Objects; -public class ByteSyncValue extends ValueSyncHandler implements IByteSyncValue { +public class ByteSyncValue extends ValueSyncHandler + implements IByteSyncValue { private byte cache; private final ByteValue.Supplier getter; diff --git a/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java b/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java index 47364e0a..c0bde9c2 100644 --- a/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/DoubleSyncValue.java @@ -14,7 +14,9 @@ import java.util.function.DoubleConsumer; import java.util.function.DoubleSupplier; -public class DoubleSyncValue extends ValueSyncHandler implements IDoubleSyncValue, IFloatSyncValue, IStringSyncValue { +public class DoubleSyncValue extends ValueSyncHandler + implements IDoubleSyncValue, IFloatSyncValue, + IStringSyncValue { private final DoubleSupplier getter; private final DoubleConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java b/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java index 950d1451..c1344754 100644 --- a/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/DynamicLinkedSyncHandler.java @@ -2,7 +2,6 @@ import brachy.modularui.api.widget.IWidget; import brachy.modularui.widget.WidgetTree; - import brachy.modularui.widgets.dynamic.IDynamicHandler; import net.minecraft.network.RegistryFriendlyByteBuf; @@ -15,13 +14,16 @@ import java.util.function.Supplier; /** - * This is a variation of {@link DynamicSyncHandler} with the difference that this is linked to a {@link ValueSyncHandler}. - * This sync handler is automatically notified, when the linked value is updated. The widget provider here has the linked sync handler as an + * This is a variation of {@link DynamicSyncHandler} with the difference that this is linked to a + * {@link ValueSyncHandler}. + * This sync handler is automatically notified, when the linked value is updated. The widget provider here has the + * linked sync handler as an * argument instead of a packet. * To use it simply pass in a registered value sync handler into the constructor and link it to a * {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. */ -public class DynamicLinkedSyncHandler> extends SyncHandler> implements IDynamicHandler { +public class DynamicLinkedSyncHandler> + extends SyncHandler> implements IDynamicHandler { private IWidgetProvider widgetProvider; private Consumer onWidgetUpdate; @@ -104,7 +106,8 @@ private void notifyUpdate(boolean sync) { * Sets a widget creator which is called on client and server. {@link SyncHandler}s can be created here using * {@link PanelSyncManager#getOrCreateSyncHandler(String, int, Class, Supplier)}. Returning null in the function * will not update the widget. - * On client side the result is handed over to a linked {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. + * On client side the result is handed over to a linked {@link brachy.modularui.widgets.dynamic.DynamicWidget + * DynamicWidget}. * * @param widgetProvider the widget creator function * @return this @@ -116,7 +119,8 @@ public DynamicLinkedSyncHandler widgetProvider(IWidgetProvider widge } /** - * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. + * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget + * DynamicWidget}. */ @ApiStatus.Internal @Override diff --git a/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java b/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java index cd33d3b1..babc106a 100644 --- a/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/DynamicSyncHandler.java @@ -132,7 +132,8 @@ public DynamicSyncHandler widgetProvider(IWidgetProvider widgetProvider) { } /** - * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget DynamicWidget}. + * An internal function which is used to link the {@link brachy.modularui.widgets.dynamic.DynamicWidget + * DynamicWidget}. */ @ApiStatus.Internal @Override diff --git a/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java b/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java index e1f5e6ca..73abec5a 100644 --- a/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/EnumSyncValue.java @@ -16,7 +16,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public class EnumSyncValue> extends ValueSyncHandler> implements IEnumValue, IIntSyncValue { +public class EnumSyncValue> extends ValueSyncHandler> + implements IEnumValue, IIntSyncValue { @Getter protected final Class enumClass; diff --git a/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java b/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java index ac1ba678..d0a2ef7a 100644 --- a/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/FloatSyncValue.java @@ -14,7 +14,9 @@ import java.util.Objects; -public class FloatSyncValue extends ValueSyncHandler implements IFloatSyncValue, IDoubleSyncValue, IStringSyncValue { +public class FloatSyncValue extends ValueSyncHandler + implements IFloatSyncValue, IDoubleSyncValue, + IStringSyncValue { private final FloatSupplier getter; private final FloatConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java b/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java index 3dfec015..c4ed71f8 100644 --- a/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/FluidSlotSyncHandler.java @@ -1,8 +1,8 @@ package brachy.modularui.value.sync; +import brachy.modularui.utils.MouseData; import brachy.modularui.utils.handlers.fluid.FluidTankHandler; import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; -import brachy.modularui.utils.MouseData; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.sounds.SoundEvent; @@ -41,11 +41,13 @@ public class FluidSlotSyncHandler extends ValueSyncHandler - * Note that if this FluidSlotSyncHandler was constructed with only a fluid tank and no fluid handler, this field's value will be + * Note that if this FluidSlotSyncHandler was constructed with only a fluid tank and no fluid handler, this field's + * value will be * {@link #UNKNOWN_TANK_INDEX} so you should check that instead of assuming it's nonnegative (>=0). */ @Accessors(fluent = false) - @Getter private final int tankIndex; + @Getter + private final int tankIndex; @Getter @Setter private boolean canFillSlot = true, canDrainSlot = true, phantom = false; @@ -176,10 +178,12 @@ private boolean fillSlot(Player player, ItemStack currentStack, int maxAttempts, if (maxAmount <= 0) return false; boolean performedTransfer = false; for (int i = 0; i < maxAttempts; i++) { - FluidActionResult result = FluidUtil.tryEmptyContainer(currentStack, this.fluidHandler, maxAmount, null, false); + FluidActionResult result = FluidUtil.tryEmptyContainer(currentStack, this.fluidHandler, maxAmount, null, + false); ItemStack remainingStack = result.getResult(); if (!result.isSuccess() || - (currentStack.getCount() > 1 && !remainingStack.isEmpty() && !player.getInventory().add(remainingStack))) { + (currentStack.getCount() > 1 && !remainingStack.isEmpty() && + !player.getInventory().add(remainingStack))) { player.drop(remainingStack, true); break; // do not continue if we can't add resulting container into inventory } @@ -203,19 +207,23 @@ private boolean fillSlot(Player player, ItemStack currentStack, int maxAttempts, return performedTransfer; } - private boolean drainSlot(Player player, ItemStack currentStack, int maxAttempts, int maxAmount, boolean playSound) { + private boolean drainSlot(Player player, ItemStack currentStack, int maxAttempts, int maxAmount, + boolean playSound) { FluidStack currentFluid = this.fluidTank.getFluid(); if (currentFluid.isEmpty() || maxAmount <= 0) return false; boolean performedTransfer = false; for (int i = 0; i < maxAttempts; i++) { - FluidActionResult result = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, null, false); + FluidActionResult result = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, null, + false); ItemStack remainingStack = result.getResult(); if (!result.isSuccess() || - (currentStack.getCount() > 1 && !remainingStack.isEmpty() && !player.getInventory().add(remainingStack))) { + (currentStack.getCount() > 1 && !remainingStack.isEmpty() && + !player.getInventory().add(remainingStack))) { break; // do not continue if we can't add resulting container into inventory } - remainingStack = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, playSound ? player : null, true).result; + remainingStack = FluidUtil.tryFillContainer(currentStack, this.fluidHandler, maxAmount, + playSound ? player : null, true).result; if (currentStack.getCount() == 1) { currentStack = remainingStack; } else { @@ -243,7 +251,8 @@ public void tryClickPhantom(MouseData mouseData) { if (this.canFillSlot) { // set slot to fluid of tank item if (fluidHandlerItem != null) { - FluidStack cellFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE); + FluidStack cellFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, + IFluidHandler.FluidAction.SIMULATE); if (!cellFluid.isEmpty()) { if (FluidStack.isSameFluidSameComponents(cellFluid, currentFluid)) { // if it already contains the same fluid increase the amount by the cells amount @@ -290,7 +299,8 @@ public void tryClickPhantom(MouseData mouseData) { } } - private void drainSlotPhantom(boolean shift, Player player, FluidStack currentFluid, IFluidHandlerItem fluidHandlerItem) { + private void drainSlotPhantom(boolean shift, Player player, FluidStack currentFluid, + IFluidHandlerItem fluidHandlerItem) { currentFluid = currentFluid.copy(); if (this.controlsAmount && !shift) { if (fluidHandlerItem != null) { @@ -366,7 +376,8 @@ public void playSound(Player player, FluidStack fluid, SoundAction action) { if (sound == null) return; // on client, it needs the player to play the sound // on server the player is an exception - player.level().playSound(getSyncManager().isClient() ? player : null, player.getX(), player.getY() + 0.5, player.getZ(), sound, + player.level().playSound(getSyncManager().isClient() ? player : null, player.getX(), player.getY() + 0.5, + player.getZ(), sound, SoundSource.BLOCKS, 1.0F, 1.0F); } diff --git a/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java index dc324f78..1a2e1023 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericCollectionSyncHandler.java @@ -17,7 +17,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public abstract class GenericCollectionSyncHandler, S extends GenericCollectionSyncHandler> extends ValueSyncHandler { +public abstract class GenericCollectionSyncHandler, + S extends GenericCollectionSyncHandler> extends ValueSyncHandler { private final Supplier getter; private final Consumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java index ff84f4c3..cabd8b88 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericListSyncHandler.java @@ -19,7 +19,8 @@ import java.util.function.IntFunction; import java.util.function.Supplier; -public class GenericListSyncHandler extends GenericCollectionSyncHandler, GenericListSyncHandler> { +public class GenericListSyncHandler + extends GenericCollectionSyncHandler, GenericListSyncHandler> { private final List cache = new ObjectArrayList<>(); @@ -69,7 +70,8 @@ public Class> getValueType() { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -79,8 +81,10 @@ public void modifyValue(Consumer> consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ @@ -93,7 +97,8 @@ public static Builder builder() { return new Builder<>(); } - public static class Builder extends GenericCollectionSyncHandler.Builder, Builder> { + public static class Builder + extends GenericCollectionSyncHandler.Builder, Builder> { public Builder getterArray(Supplier getter) { getter(() -> Arrays.asList(getter.get())); diff --git a/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java index c8f34120..c0ed2451 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericMapSyncHandler.java @@ -17,7 +17,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public class GenericMapSyncHandler extends ValueSyncHandler, GenericMapSyncHandler> { +public class GenericMapSyncHandler + extends ValueSyncHandler, GenericMapSyncHandler> { private final Supplier> getter; private final Consumer> setter; @@ -129,7 +130,8 @@ public Class> getValueType() { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -139,8 +141,10 @@ public void modifyValue(Consumer> consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ diff --git a/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java b/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java index 9ea49e37..54518976 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/GenericSetSyncHandler.java @@ -16,7 +16,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public class GenericSetSyncHandler extends GenericCollectionSyncHandler, GenericSetSyncHandler> { +public class GenericSetSyncHandler + extends GenericCollectionSyncHandler, GenericSetSyncHandler> { private final Set cache = new ObjectOpenHashSet(); @@ -64,7 +65,8 @@ public Class> getValueType() { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. * This method forces a sync after the modification. * * @param consumer function that operates on the current cached value @@ -74,8 +76,10 @@ public void modifyValue(Consumer> consumer) { } /** - * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be synced. - * This method can automatically sync the cache after the modification. Be careful with potential issues when the sync arg is false. + * Allows safe modification of the cached value. Normally modifying the cached value can cause the value to never be + * synced. + * This method can automatically sync the cache after the modification. Be careful with potential issues when the + * sync arg is false. * * @param consumer function that operates on the current cached value */ @@ -88,7 +92,8 @@ public static Builder builder() { return new Builder<>(); } - public static class Builder extends GenericCollectionSyncHandler.Builder, Builder> { + public static class Builder + extends GenericCollectionSyncHandler.Builder, Builder> { public GenericSetSyncHandler build() { if (this.getter == null) throw new NullPointerException("Getter in GenericSetSyncHandler must not be null"); diff --git a/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java b/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java index d8c778b8..dc1eb1b5 100644 --- a/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/GenericSyncValue.java @@ -30,14 +30,20 @@ * Example: * GenericSyncValue.builder(ItemStack.class) *

- * When you work with types which themselves have generic types, then your IDE will likely yell at you. In this case you can use - * {@link #rawTypeBuilder(Class)}. Only use this if you have to, since you can technically put any class inside there without ModularUI be - * able to verify it. Since you can't specify the type {@link T} with the type here you need to use the diamond operator. + * When you work with types which themselves have generic types, then your IDE will likely yell at you. In this case you + * can use + * {@link #rawTypeBuilder(Class)}. Only use this if you have to, since you can technically put any class inside there + * without ModularUI be + * able to verify it. Since you can't specify the type {@link T} with the type here you need to use the diamond + * operator. *

* Example: GenericSyncValue.<List<ItemStack>>rawTypeBuilder(List.class) - *
Note that you wouldn't actually use {@link java.util.List List} here. It's just an example for a type with a generic parameter. + *
+ * Note that you wouldn't actually use {@link java.util.List List} here. It's just an example for a type with a generic + * parameter. *

- * If the value is never null you can also use {@link #notNullBuilder()}. This will infer the type with the value supplier. + * If the value is never null you can also use {@link #notNullBuilder()}. This will infer the type with the value + * supplier. *

* Example: GenericSyncValue.<ItemStack>notNullBuilder() *

@@ -142,7 +148,8 @@ public static Builder builder(Class type) { /** * Creates a builder for a generic sync value. This method should only be used if the type has generic parameters. - * The downside of this method is that the compiler can't verify the passed in class. Technically any class can be passed on, + * The downside of this method is that the compiler can't verify the passed in class. Technically any class can be + * passed on, * but issues will arise later down the line. * * @param type Class of the value to sync. This is used to verify synced value types. @@ -184,10 +191,14 @@ private Builder(Class type) { } /** - * Sets the getter for the sync value. Usually this returns a field in a {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or - * similar. On server side this is called every tick and compared to the sync values cache. If the values are different + * Sets the getter for the sync value. Usually this returns a field in a + * {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or + * similar. On server side this is called every tick and compared to the sync values cache. If the values are + * different * (determined by {@link #equals(EqualityTest)}), it is synced to the client. - *

This setter is required!

+ *

+ * This setter is required! + *

* * @param getter function that returns the current value that may be synced * @return this builder @@ -198,10 +209,14 @@ public Builder getter(Supplier<@UnknownNullability T> getter) { } /** - * Sets the setter for the sync value. Usually this sets a field in a {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or - * similar. This is called when a value is synced in client or server. In many cases this can be null since the synced value is + * Sets the setter for the sync value. Usually this sets a field in a + * {@link net.minecraft.world.level.block.entity.BlockEntity BlockEntity} or + * similar. This is called when a value is synced in client or server. In many cases this can be null since the + * synced value is * cached inside the sync handler. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @param setter function that updates the source of the value * @return this builder @@ -212,9 +227,12 @@ public Builder setter(Consumer<@UnknownNullability T> setter) { } /** - * Sets a function which writes the value to a {@link FriendlyByteBuf}. The function is called every time the value is synced to the + * Sets a function which writes the value to a {@link FriendlyByteBuf}. The function is called every time the + * value is synced to the * other side. - *

This setter is required!

+ *

+ * This setter is required! + *

* * @param deserializer function that writes the value to a packet buffer * @return this builder @@ -225,9 +243,12 @@ public Builder deserializer(StreamDecoder deseri } /** - * Sets a function which reads the value from a {@link FriendlyByteBuf}. The function is called every time the value is synced to the + * Sets a function which reads the value from a {@link FriendlyByteBuf}. The function is called every time the + * value is synced to the * other side. - *

This setter is required!

+ *

+ * This setter is required! + *

* * @param serializer function that reads the value from a packet buffer * @return this builder @@ -238,12 +259,18 @@ public Builder serializer(StreamEncoder serializ } /** - * Sets a function which tests two instances of the value for differences. This function is called every tick on server to determine - * if the value from {@link #getter(Supplier)} needs to be synced. By default, this uses {@link Objects#equals(Object, Object)}. - * If your value does not implement {@link Object#equals(Object)}, then this setter must be called in order for it to function - * properly. Otherwise {@link Objects#equals(Object, Object)} always returns false since the instances will always be different, + * Sets a function which tests two instances of the value for differences. This function is called every tick on + * server to determine + * if the value from {@link #getter(Supplier)} needs to be synced. By default, this uses + * {@link Objects#equals(Object, Object)}. + * If your value does not implement {@link Object#equals(Object)}, then this setter must be called in order for + * it to function + * properly. Otherwise {@link Objects#equals(Object, Object)} always returns false since the instances will + * always be different, * which causes the value to be synced every tick. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @param equals function that determines if two instances of the value are equal * @return this builder @@ -264,20 +291,30 @@ public Builder equalsDefault() { } /** - * Sets a function which creates a copy of the value. This is called every time the value cache is updated. This is to prevent - * accidental mutations of the cache value. For example if you called {@link #setValue(Object)}, but keep a reference to the new - * value and then modify your reference, then the cached value is also updated since it's the same object. If now the - * {@link #getter(Supplier)} function happens to return exactly that reference, then the {@link #equals(EqualityTest)} function always - * compares its cache to itself (since it compare the cache to the getter value, which are the same in this case). This causes + * Sets a function which creates a copy of the value. This is called every time the value cache is updated. This + * is to prevent + * accidental mutations of the cache value. For example if you called {@link #setValue(Object)}, but keep a + * reference to the new + * value and then modify your reference, then the cached value is also updated since it's the same object. If + * now the + * {@link #getter(Supplier)} function happens to return exactly that reference, then the + * {@link #equals(EqualityTest)} function always + * compares its cache to itself (since it compare the cache to the getter value, which are the same in this + * case). This causes * the value to be never synced from server to client. *

- * By default, the {@link #serializer(StreamEncoder)} and {@link #deserializer(StreamDecoder)} function are called to - * create a new instance. If these functions are implemented properly, it is always guaranteed to create a new instance of the + * By default, the {@link #serializer(StreamEncoder)} and {@link #deserializer(StreamDecoder)} function are + * called to + * create a new instance. If these functions are implemented properly, it is always guaranteed to create a new + * instance of the * value. However, it is still recommended to provide your own proper copy method. *

- * If you know, that your values is immutable (can't be modified once created), then you can use {@link #copyImmutable()}. + * If you know, that your values is immutable (can't be modified once created), then you can use + * {@link #copyImmutable()}. * That function won't copy the value, but just return the value. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @param copy function that creates a new exact copy of the value * @return this builder @@ -288,7 +325,8 @@ public Builder copy(ICopy<@UnknownNullability T> copy) { } /** - * Sets a {@link #copy(ICopy)} function which assumes the values are always immutable. This should only be used if the value is + * Sets a {@link #copy(ICopy)} function which assumes the values are always immutable. This should only be used + * if the value is * always immutable (can't be modified once created). See {@link #copy(ICopy)} for more info. * * @return this builder @@ -315,10 +353,13 @@ public Builder adapter(IByteBufAdapter adapter) } /** - * Sets the value to be nullable. This wraps all the used functions into null safe variants. This only for convenience. + * Sets the value to be nullable. This wraps all the used functions into null safe variants. This only for + * convenience. * Manually having to consider nullability inside all the functions is cumbersome. This setter is a shortcut. * It is opt-in since, it creates a very minor overhead in the serializer and deserializer. - *

This setter is optional!

+ *

+ * This setter is optional! + *

* * @return this builder */ @@ -340,7 +381,8 @@ public Builder allowC2S() { * @throws IllegalArgumentException if the value type is null and the getter returns null */ public GenericSyncValue build() { - return new GenericSyncValue<>(type, getter, setter, deserializer, serializer, equals, copy, nullable).allowC2S(this.allowC2S); + return new GenericSyncValue<>(type, getter, setter, deserializer, serializer, equals, copy, nullable) + .allowC2S(this.allowC2S); } } } diff --git a/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java b/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java index 960d4be6..6ec47306 100644 --- a/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java +++ b/src/main/java/brachy/modularui/value/sync/ISyncRegistrar.java @@ -47,7 +47,8 @@ default DynamicSyncHandler dynamicSyncHandler(String key, DynamicSyncHandler.IWi return dynamicSyncHandler(key, 0, widgetProvider); } - default DynamicSyncHandler dynamicSyncHandler(String key, int id, DynamicSyncHandler.IWidgetProvider widgetProvider) { + default DynamicSyncHandler dynamicSyncHandler(String key, int id, + DynamicSyncHandler.IWidgetProvider widgetProvider) { DynamicSyncHandler syncHandler = new DynamicSyncHandler().widgetProvider(widgetProvider); syncValue(key, id, syncHandler); return syncHandler; @@ -55,12 +56,14 @@ default DynamicSyncHandler dynamicSyncHandler(String key, int id, DynamicSyncHan IPanelHandler syncedPanel(String key, boolean subPanel, PanelSyncHandler.IPanelBuilder panelBuilder); - @Nullable IPanelHandler findPanelHandlerNullable(String key); + @Nullable + IPanelHandler findPanelHandlerNullable(String key); default @NotNull IPanelHandler findPanelHandler(String key) { IPanelHandler panelHandler = findPanelHandlerNullable(key); if (panelHandler == null) { - throw new NoSuchElementException("Expected to find panel sync handler with key '" + key + "', but none was found."); + throw new NoSuchElementException( + "Expected to find panel sync handler with key '" + key + "', but none was found."); } return panelHandler; } @@ -134,10 +137,12 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, Supplier s } default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier slotSupplier) { - return getOrCreateSyncHandler(name, id, ItemSlotSyncHandler.class, () -> new ItemSlotSyncHandler(slotSupplier.get())); + return getOrCreateSyncHandler(name, id, ItemSlotSyncHandler.class, + () -> new ItemSlotSyncHandler(slotSupplier.get())); } - @Nullable SyncHandler findSyncHandlerNullable(String name, int id); + @Nullable + SyncHandler findSyncHandlerNullable(String name, int id); default @Nullable SyncHandler findSyncHandlerNullable(String name) { return findSyncHandlerNullable(name, 0); @@ -146,7 +151,8 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier findSyncHandler(String name, int id) { SyncHandler syncHandler = findSyncHandlerNullable(name, id); if (syncHandler == null) { - throw new NoSuchElementException("Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); + throw new NoSuchElementException( + "Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); } return syncHandler; } @@ -170,11 +176,12 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier> @NotNull T findSyncHandler(String name, int id, Class type) { SyncHandler syncHandler = findSyncHandlerNullable(name, id); if (syncHandler == null) { - throw new NoSuchElementException("Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); + throw new NoSuchElementException( + "Expected to find sync handler with key '" + makeSyncKey(name, id) + "', but none was found."); } if (!type.isAssignableFrom(syncHandler.getClass())) { - throw new ClassCastException("Expected to find sync handler with key '" + makeSyncKey(name, id) + "' of type '" + type.getName() - + "', but found type '" + syncHandler.getClass().getName() + "'."); + throw new ClassCastException("Expected to find sync handler with key '" + makeSyncKey(name, id) + + "' of type '" + type.getName() + "', but found type '" + syncHandler.getClass().getName() + "'."); } return type.cast(syncHandler); } @@ -195,7 +202,8 @@ default ItemSlotSyncHandler getOrCreateSlot(String name, int id, Supplier> @NotNull Optional findSyncHandlerOptional(String name, int id, Class type) { + default > @NotNull Optional findSyncHandlerOptional(String name, int id, + Class type) { return Optional.ofNullable(findSyncHandlerNullable(name, id, type)); } diff --git a/src/main/java/brachy/modularui/value/sync/IntSyncValue.java b/src/main/java/brachy/modularui/value/sync/IntSyncValue.java index 0db80242..7653db2d 100644 --- a/src/main/java/brachy/modularui/value/sync/IntSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/IntSyncValue.java @@ -16,7 +16,9 @@ import java.util.function.IntConsumer; import java.util.function.IntSupplier; -public class IntSyncValue extends ValueSyncHandler implements IIntSyncValue, IDoubleSyncValue, IStringSyncValue { +public class IntSyncValue extends ValueSyncHandler + implements IIntSyncValue, IDoubleSyncValue, + IStringSyncValue { private int cache; private final IntSupplier getter; diff --git a/src/main/java/brachy/modularui/value/sync/LongSyncValue.java b/src/main/java/brachy/modularui/value/sync/LongSyncValue.java index 7121b0fa..e03c3ab8 100644 --- a/src/main/java/brachy/modularui/value/sync/LongSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/LongSyncValue.java @@ -16,7 +16,9 @@ import java.util.function.LongConsumer; import java.util.function.LongSupplier; -public class LongSyncValue extends ValueSyncHandler implements ILongSyncValue, IIntSyncValue, IStringSyncValue { +public class LongSyncValue extends ValueSyncHandler + implements ILongSyncValue, IIntSyncValue, + IStringSyncValue { private final LongSupplier getter; private final LongConsumer setter; diff --git a/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java b/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java index 53dc56f4..ef4f3e7c 100644 --- a/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java +++ b/src/main/java/brachy/modularui/value/sync/ModularSyncManager.java @@ -80,7 +80,8 @@ public void onOpen() { if (isOpen()) return; if (isDisposed()) throw new IllegalStateException("Can't open sync manager after it has been disposed!"); if (this.menu == null) { - throw new IllegalStateException("Sync Manager can't be opened when its not yet constructed. ModularContainer is null."); + throw new IllegalStateException( + "Sync Manager can't be opened when its not yet constructed. ModularContainer is null."); } setState(State.OPEN); this.panelSyncManagerMap.values().forEach(PanelSyncManager::onOpen); @@ -138,12 +139,14 @@ public boolean isOpen(String panelName) { } @ApiStatus.Internal - public void receiveWidgetUpdate(String panelName, String mapKey, boolean action, int id, RegistryFriendlyByteBuf buf) { + public void receiveWidgetUpdate(String panelName, String mapKey, boolean action, int id, + RegistryFriendlyByteBuf buf) { PanelSyncManager psm = this.panelSyncManagerMap.get(panelName); if (psm != null) { psm.receiveWidgetUpdate(mapKey, action, id, buf); } else if (!this.panelHistory.contains(panelName)) { - ModularUI.LOGGER.throwing(new IllegalStateException("A packet was send to panel '" + panelName + "' which was not opened yet!.")); + ModularUI.LOGGER.throwing(new IllegalStateException( + "A packet was send to panel '" + panelName + "' which was not opened yet!.")); } // else the panel was open at some point // we simply discard the packet silently and assume the packet was correctly send, but the panel closed earlier @@ -195,13 +198,15 @@ public ModularSyncManager registerSlotGroup(SlotGroup slotGroup) { } @Override - public ModularSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, ISyncedAction action) { + public ModularSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, + ISyncedAction action) { this.mainPSM.registerSyncedAction(mapKey, executeClient, executeServer, action); return this; } @Override - public > T getOrCreateSyncHandler(String name, int id, Class clazz, Supplier supplier) { + public > T getOrCreateSyncHandler(String name, int id, Class clazz, + Supplier supplier) { return this.mainPSM.getOrCreateSyncHandler(name, id, clazz, supplier); } @@ -237,6 +242,9 @@ private void setState(State state) { } enum State { - INIT, OPEN, CLOSED, DISPOSED + INIT, + OPEN, + CLOSED, + DISPOSED } } diff --git a/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java b/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java index 5b755f49..32e969be 100644 --- a/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java +++ b/src/main/java/brachy/modularui/value/sync/PanelSyncManager.java @@ -69,7 +69,8 @@ public void initialize(String panelName) { this.locked = true; this.syncHandlers.forEach((mapKey, syncHandler) -> syncHandler.init(mapKey, this)); this.init = true; - this.subPanels.forEach((s, syncHandler) -> this.modularSyncManager.getMainPSM().registerPanelSyncHandler(s, syncHandler)); + this.subPanels.forEach( + (s, syncHandler) -> this.modularSyncManager.getMainPSM().registerPanelSyncHandler(s, syncHandler)); } private void registerPanelSyncHandler(String name, SyncHandler syncHandler) { @@ -81,8 +82,9 @@ private void registerPanelSyncHandler(String name, SyncHandler syncHandler) { } String currentName = this.reverseSyncHandlers.get(syncHandler); if (currentName != null && !name.equals(currentName)) { - throw new IllegalStateException("Failed to register panel sync handler for name '" + name + "' during initialization. " + - "The panel sync handler is already registered under the name '" + currentName + "'."); + throw new IllegalStateException( + "Failed to register panel sync handler for name '" + name + "' during initialization. " + + "The panel sync handler is already registered under the name '" + currentName + "'."); } this.syncHandlers.put(name, syncHandler); this.reverseSyncHandlers.put(syncHandler, name); @@ -106,7 +108,8 @@ public void onOpen() { public void onClose() { this.closeListener.forEach(listener -> listener.accept(getPlayer())); this.syncHandlers.values().forEach(SyncHandler::dispose); - // Previously panel sync handlers were removed from the main psm, however this problematic if the screen will be reopened at some + // Previously panel sync handlers were removed from the main psm, however this problematic if the screen will be + // reopened at some // point. We can just not remove the sync handlers since mui has proper checks for re-registering panels. } @@ -143,7 +146,8 @@ public void receiveWidgetUpdate(String mapKey, boolean action, int id, RegistryF } else if (syncHandler.isAllowC2S()) { syncHandler.readOnServer(id, buf); } else { - ModularUI.LOGGER.throwing(Level.WARN, new SecurityException("Tried to send a packet to server, but the sync handler does not accept client packets.")); + ModularUI.LOGGER.throwing(Level.WARN, new SecurityException( + "Tried to send a packet to server, but the sync handler does not accept client packets.")); } } @@ -153,7 +157,8 @@ private boolean invokeSyncedAction(String mapKey, RegistryFriendlyByteBuf buf) { ModularUI.LOGGER.warn("SyncAction '{}' does not exist for panel '{}'!.", mapKey, panelName); return false; } - if (!isLocked() || this.allowSyncHandlerRegistration || !syncedAction.isExecuteClient() || !syncedAction.isExecuteServer()) { + if (!isLocked() || this.allowSyncHandlerRegistration || !syncedAction.isExecuteClient() || + !syncedAction.isExecuteServer()) { syncedAction.invoke(this.client, buf); } else { // only allow sync handler registration if it is executed on client and server @@ -184,9 +189,11 @@ private void putSyncValue(String name, int id, SyncHandler syncHandler) { // registration of sync handlers forbidden if (this.allowSyncHandlerRegistration) { // lock can be bypassed currently, but it wasn't used - throw new IllegalStateException("SyncHandlers must be registered during panel building. Please use getOrCreateSyncHandler() inside DynamicSyncHandler!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. Please use getOrCreateSyncHandler() inside DynamicSyncHandler!"); } else { - throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } } String key = makeSyncKey(name, id); @@ -225,13 +232,17 @@ public PanelSyncManager syncValue(String name, int id, SyncHandler syncHandle * NOTE *

* A panel sync handler is only created once. If one was already registered, that one will be returned. - * (This is only relevant for nested sub panels.) Furthermore, the panel handler has to be created on client and server with the same - * key. Like any other sync handler, the panel sync handler has to be created before the panel opened. The only exception is inside + * (This is only relevant for nested sub panels.) Furthermore, the panel handler has to be created on client and + * server with the same + * key. Like any other sync handler, the panel sync handler has to be created before the panel opened. The only + * exception is inside * dynamic sync handlers. * * @param key the key used for syncing - * @param subPanel true if this panel should close when its parent closes (the parent is defined by this {@link PanelSyncManager}) - * @param panelBuilder the panel builder, that will create the new panel. It must not return null or any existing panels. + * @param subPanel true if this panel should close when its parent closes (the parent is defined by this + * {@link PanelSyncManager}) + * @param panelBuilder the panel builder, that will create the new panel. It must not return null or any existing + * panels. * @return a synced panel handler. * @throws NullPointerException if the build panel of the builder is null * @throws IllegalArgumentException if the build panel of the builder is the main panel @@ -243,12 +254,14 @@ public IPanelHandler syncedPanel(String key, boolean subPanel, PanelSyncHandler. if (ph != null) return ph; if (isLocked() && !this.allowSyncHandlerRegistration) { // registration of sync handlers forbidden - throw new IllegalStateException("Synced panels must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "Synced panels must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } PanelSyncHandler syncHandler = new PanelSyncHandler(panelBuilder, subPanel); this.subPanels.put(key, syncHandler); if (isInitialised() && (this == this.modularSyncManager.getMainPSM() || - this.modularSyncManager.getMainPSM().findSyncHandlerNullable(this.panelName, PanelSyncHandler.class) == null)) { + this.modularSyncManager.getMainPSM().findSyncHandlerNullable(this.panelName, PanelSyncHandler.class) == + null)) { // current panel is open this.modularSyncManager.getMainPSM().registerPanelSyncHandler(key, syncHandler); } @@ -304,7 +317,8 @@ public PanelSyncManager onCommonTick(Runnable runnable) { } @Override - public PanelSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, ISyncedAction action) { + public PanelSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, + ISyncedAction action) { if (executeClient || executeServer) { this.syncedActions.put(mapKey, new SyncedAction(action, executeClient, executeServer)); } @@ -313,7 +327,8 @@ public PanelSyncManager registerSyncedAction(String mapKey, boolean executeClien public void callSyncedAction(String mapKey, RegistryFriendlyByteBuf packet) { if (invokeSyncedAction(mapKey, packet)) { - ModularNetwork.get(isClient()).sendActionPacket(getModularSyncManager(), this.panelName, mapKey, packet, getPlayer()); + ModularNetwork.get(isClient()).sendActionPacket(getModularSyncManager(), this.panelName, mapKey, packet, + getPlayer()); } } @@ -328,12 +343,14 @@ public void callSyncedAction(String mapKey) { } @Override - public > T getOrCreateSyncHandler(String name, int id, Class clazz, Supplier supplier) { + public > T getOrCreateSyncHandler(String name, int id, Class clazz, + Supplier supplier) { SyncHandler syncHandler = findSyncHandlerNullable(name, id); if (syncHandler == null) { if (isLocked() && !this.allowSyncHandlerRegistration) { // registration is locked, and we don't have permission to temporarily bypass lock - throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } T t = supplier.get(); boolean l = this.locked; @@ -345,7 +362,8 @@ public > T getOrCreateSyncHandler(String name, int id, if (clazz.isAssignableFrom(syncHandler.getClass())) { return clazz.cast(syncHandler); } - throw new IllegalStateException("SyncHandler for key " + makeSyncKey(name, id) + " is of type " + syncHandler.getClass() + ", but type " + clazz + " was expected!"); + throw new IllegalStateException("SyncHandler for key " + makeSyncKey(name, id) + " is of type " + + syncHandler.getClass() + ", but type " + clazz + " was expected!"); } @Override @@ -354,7 +372,8 @@ public > T getOrCreateSyncHandler(String name, int id, if (syncHandler == null) { if (isLocked() && !this.allowSyncHandlerRegistration) { // registration is locked, and we don't have permission to temporarily bypass lock - throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); + throw new IllegalStateException( + "SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!"); } T t = supplier.get(); boolean l = this.locked; @@ -364,7 +383,7 @@ public > T getOrCreateSyncHandler(String name, int id, return t; } try { - //noinspection unchecked + // noinspection unchecked return (T) syncHandler; } catch (ClassCastException e) { throw new IllegalStateException("SyncHandler for key " + makeSyncKey(name, id) + diff --git a/src/main/java/brachy/modularui/value/sync/PhantomItemSlotSyncHandler.java b/src/main/java/brachy/modularui/value/sync/PhantomItemSlotSyncHandler.java index 0c7c0a6d..239496f9 100644 --- a/src/main/java/brachy/modularui/value/sync/PhantomItemSlotSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/PhantomItemSlotSyncHandler.java @@ -6,9 +6,9 @@ import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.InputConstants; import net.neoforged.api.distmarker.Dist; +import com.mojang.blaze3d.platform.InputConstants; import org.jetbrains.annotations.ApiStatus; /** @@ -101,7 +101,8 @@ protected void phantomClick(MouseData mouseData, ItemStack cursorStack) { this.lastStoredPhantomItem = stackToPut.copy(); } else if (slotStack.isEmpty()) { if (cursorStack.isEmpty()) { - if (mouseData.mouseButton() == InputConstants.MOUSE_BUTTON_RIGHT && !this.lastStoredPhantomItem.isEmpty()) { + if (mouseData.mouseButton() == InputConstants.MOUSE_BUTTON_RIGHT && + !this.lastStoredPhantomItem.isEmpty()) { stackToPut = this.lastStoredPhantomItem.copy(); } else { return; diff --git a/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java b/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java index 1ef7a69a..1fc76327 100644 --- a/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/ShortSyncValue.java @@ -13,7 +13,9 @@ import java.util.Objects; -public class ShortSyncValue extends ValueSyncHandler implements IShortSyncValue, IIntSyncValue, IStringSyncValue { +public class ShortSyncValue extends ValueSyncHandler + implements IShortSyncValue, IIntSyncValue, + IStringSyncValue { private short cache; private final ShortValue.Supplier getter; diff --git a/src/main/java/brachy/modularui/value/sync/StringSyncValue.java b/src/main/java/brachy/modularui/value/sync/StringSyncValue.java index 7a4c4cd4..eeb11fde 100644 --- a/src/main/java/brachy/modularui/value/sync/StringSyncValue.java +++ b/src/main/java/brachy/modularui/value/sync/StringSyncValue.java @@ -12,7 +12,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -public class StringSyncValue extends AbstractGenericSyncValue implements IStringSyncValue { +public class StringSyncValue extends AbstractGenericSyncValue + implements IStringSyncValue { public StringSyncValue(Supplier getter, Consumer setter) { super(String.class, getter, setter); diff --git a/src/main/java/brachy/modularui/value/sync/SyncHandler.java b/src/main/java/brachy/modularui/value/sync/SyncHandler.java index adf8ab89..2d491eda 100644 --- a/src/main/java/brachy/modularui/value/sync/SyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/SyncHandler.java @@ -11,7 +11,6 @@ import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; - import io.netty.buffer.Unpooled; import lombok.Getter; import org.apache.logging.log4j.Level; @@ -32,8 +31,10 @@ public abstract class SyncHandler> implements ISyncOrVa /** * the key that belongs to this sync handler */ - @Getter private String key; - @Getter private boolean allowC2S; + @Getter + private String key; + @Getter + private boolean allowC2S; @ApiStatus.OverrideOnly @MustBeInvokedByOverriders @@ -71,7 +72,8 @@ public final void syncToClient(int id, @NotNull IPacketWriter bufferConsumer) { if (!isAllowC2S()) { - ModularUI.LOGGER.throwing(Level.WARN, new SecurityException("Sync handler is unable to send packets to server!")); + ModularUI.LOGGER.throwing(Level.WARN, + new SecurityException("Sync handler is unable to send packets to server!")); return; } RegistryFriendlyByteBuf buffer = SidedAccessHelper.makeRegistryByteBuf(Unpooled.buffer()); @@ -88,7 +90,8 @@ public final void syncToServer(int id, @NotNull IPacketWriter bufferConsumer) { if (getSyncManager().isClient() && !isAllowC2S()) { - ModularUI.LOGGER.throwing(Level.WARN, new SecurityException("Sync handler is unable to send packets to server!")); + ModularUI.LOGGER.throwing(Level.WARN, + new SecurityException("Sync handler is unable to send packets to server!")); return; } RegistryFriendlyByteBuf buffer = SidedAccessHelper.makeRegistryByteBuf(Unpooled.buffer()); @@ -181,8 +184,10 @@ public boolean isSyncHandler() { } /** - * Sets this sync handler to accept C2S (client to server) packets. This value MUST be the same on client and server. - * By default, this is false to prevent clients from force updating values. Values which the player can control through a button for + * Sets this sync handler to accept C2S (client to server) packets. This value MUST be the same on client and + * server. + * By default, this is false to prevent clients from force updating values. Values which the player can control + * through a button for * example are completely fine to allow C2S updates. * * @param allowC2S whether this sync handler should allow client to server updates @@ -194,8 +199,10 @@ public S allowC2S(boolean allowC2S) { } /** - * Sets this sync handler whether to accept C2S (client to server) packets or not. This value MUST be the same on client and server. - * By default, this is false to prevent clients from force updating values. Values which the player can control through a button for + * Sets this sync handler whether to accept C2S (client to server) packets or not. This value MUST be the same on + * client and server. + * By default, this is false to prevent clients from force updating values. Values which the player can control + * through a button for * example are completely fine to allow C2S updates. * * @return this @@ -209,7 +216,8 @@ public S self() { return (S) this; } - private static void send(ModularNetworkSide network, String panel, RegistryFriendlyByteBuf packet, SyncHandler syncHandler) { + private static void send(ModularNetworkSide network, String panel, RegistryFriendlyByteBuf packet, + SyncHandler syncHandler) { Objects.requireNonNull(packet); Objects.requireNonNull(syncHandler); if (!syncHandler.isValid()) { diff --git a/src/main/java/brachy/modularui/value/sync/SyncHandlers.java b/src/main/java/brachy/modularui/value/sync/SyncHandlers.java index c6cd28a1..db21390d 100644 --- a/src/main/java/brachy/modularui/value/sync/SyncHandlers.java +++ b/src/main/java/brachy/modularui/value/sync/SyncHandlers.java @@ -1,10 +1,10 @@ package brachy.modularui.value.sync; +import brachy.modularui.widgets.slot.ModularSlot; + import net.neoforged.neoforge.fluids.IFluidTank; import net.neoforged.neoforge.items.IItemHandlerModifiable; -import brachy.modularui.widgets.slot.ModularSlot; - import io.netty.buffer.ByteBuf; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; diff --git a/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java b/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java index f993ed07..4d8692b2 100644 --- a/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java +++ b/src/main/java/brachy/modularui/value/sync/ValueSyncHandler.java @@ -8,7 +8,8 @@ import lombok.Getter; import lombok.Setter; -public abstract class ValueSyncHandler> extends SyncHandler implements IValueSyncHandler { +public abstract class ValueSyncHandler> extends SyncHandler + implements IValueSyncHandler { public static final int SYNC_VALUE = 0; diff --git a/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java b/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java index 9c9506de..7aa68435 100644 --- a/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java +++ b/src/main/java/brachy/modularui/widget/AbstractScrollWidget.java @@ -26,12 +26,13 @@ * @param type of this widget */ public abstract class AbstractScrollWidget> - extends AbstractParentWidget implements IViewport, Interactable { + extends AbstractParentWidget implements IViewport, Interactable { private final ScrollArea scroll = new ScrollArea(); private boolean scrollXActive, scrollYActive; - @Getter private boolean showScrollShadows = true; + @Getter + private boolean showScrollShadows = true; public AbstractScrollWidget(@Nullable HorizontalScrollData x, @Nullable VerticalScrollData y) { super(); @@ -76,8 +77,10 @@ public void beforeResize(boolean onOpen) { } protected void checkScrollbarActive(boolean resizeOnChange) { - boolean scrollYActive = this.scroll.getScrollY() != null && this.scroll.getScrollY().isScrollBarActive(getScrollArea()); - boolean scrollXActive = this.scroll.getScrollX() != null && this.scroll.getScrollX().isScrollBarActive(getScrollArea(), scrollYActive); + boolean scrollYActive = this.scroll.getScrollY() != null && + this.scroll.getScrollY().isScrollBarActive(getScrollArea()); + boolean scrollXActive = this.scroll.getScrollX() != null && + this.scroll.getScrollX().isScrollBarActive(getScrollArea(), scrollYActive); if (resizeOnChange && (scrollYActive != this.scrollYActive || scrollXActive != this.scrollXActive)) { scheduleResize(); } @@ -142,7 +145,8 @@ public void postDraw(ModularGuiContext context, boolean transformed) { if (!transformed) { context.getStencil().pop(); WidgetThemeEntry scrollbarTheme = getTheme().getScrollbarThemeEntry(); - this.scroll.drawScrollbar(context, scrollbarTheme.getTheme(isHovering()), scrollbarTheme.theme().getBackground()); + this.scroll.drawScrollbar(context, scrollbarTheme.getTheme(isHovering()), + scrollbarTheme.theme().getBackground()); if (this.showScrollShadows) this.scroll.drawScrollShadow(context); } } diff --git a/src/main/java/brachy/modularui/widget/InternalWidgetTree.java b/src/main/java/brachy/modularui/widget/InternalWidgetTree.java index 628aa8da..86f2a14b 100644 --- a/src/main/java/brachy/modularui/widget/InternalWidgetTree.java +++ b/src/main/java/brachy/modularui/widget/InternalWidgetTree.java @@ -9,9 +9,9 @@ import brachy.modularui.widgets.layout.IExpander; import net.minecraft.client.gui.GuiGraphics; -import com.mojang.blaze3d.systems.RenderSystem; import com.google.common.base.Joiner; +import com.mojang.blaze3d.systems.RenderSystem; import org.jetbrains.annotations.Contract; import java.util.ArrayList; diff --git a/src/main/java/brachy/modularui/widget/ParentWidget.java b/src/main/java/brachy/modularui/widget/ParentWidget.java index 53243ba6..08a91eb6 100755 --- a/src/main/java/brachy/modularui/widget/ParentWidget.java +++ b/src/main/java/brachy/modularui/widget/ParentWidget.java @@ -9,7 +9,7 @@ * @param type of this widget */ public class ParentWidget> extends AbstractParentWidget - implements IParentWidget { + implements IParentWidget { public boolean addChild(IWidget child, int index) { return super.addChild(child, index); diff --git a/src/main/java/brachy/modularui/widget/ScrollWidget.java b/src/main/java/brachy/modularui/widget/ScrollWidget.java index c1139d72..962aec24 100755 --- a/src/main/java/brachy/modularui/widget/ScrollWidget.java +++ b/src/main/java/brachy/modularui/widget/ScrollWidget.java @@ -6,7 +6,7 @@ import brachy.modularui.widget.scroll.VerticalScrollData; public class ScrollWidget> extends AbstractScrollWidget - implements IParentWidget { + implements IParentWidget { public ScrollWidget() { super(null, null); diff --git a/src/main/java/brachy/modularui/widget/Widget.java b/src/main/java/brachy/modularui/widget/Widget.java index efe3a710..49b77cbc 100644 --- a/src/main/java/brachy/modularui/widget/Widget.java +++ b/src/main/java/brachy/modularui/widget/Widget.java @@ -31,7 +31,6 @@ import brachy.modularui.widgets.slot.ItemSlot; import com.mojang.serialization.Codec; - import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -65,18 +64,23 @@ public class Widget> extends AbstractWidget implements IPosi .addOpt("name", Widget::name, Widget::getName, Codec.STRING, null) .addOpt("enabled", Widget::setEnabled, Widget::isEnabled, Codec.BOOL, true) .addOpt("syncKey", Widget::setSyncKey, Widget::getSyncKey, Codec.STRING, null) - .addOpt("disableThemeBackground", Widget::disableThemeBackground, Widget::isDisableThemeBackground, Codec.BOOL, false) - .addOpt("disableHoverThemeBackground", Widget::disableHoverThemeBackground, Widget::isDisableHoverThemeBackground, Codec.BOOL, false) + .addOpt("disableThemeBackground", Widget::disableThemeBackground, Widget::isDisableThemeBackground, + Codec.BOOL, false) + .addOpt("disableHoverThemeBackground", Widget::disableHoverThemeBackground, + Widget::isDisableHoverThemeBackground, Codec.BOOL, false) .addOpt("shadow", Widget::shadow, Widget::getShadow, IDrawable.CODEC, null) .addOpt("background", Widget::setBackground, Widget::getBackground, IDrawable.CODEC, null) .addOpt("backgroundOverlay", Widget::setBackground, Widget::getBackground, IDrawable.CODEC, null) .addOpt("overlay", Widget::overlay, Widget::getOverlay, IDrawable.CODEC, null) .addOpt("hoverBackground", Widget::setHoverBackground, Widget::getHoverBackground, IDrawable.CODEC, null) - .addOpt("hoverBackgroundOverlay", Widget::setHoverBackgroundOverlay, Widget::getHoverBackground, IDrawable.CODEC, null) + .addOpt("hoverBackgroundOverlay", Widget::setHoverBackgroundOverlay, Widget::getHoverBackground, + IDrawable.CODEC, null) .addOpt("hoverOverlay", Widget::hoverOverlay, Widget::getHoverOverlay, IDrawable.CODEC, null) - .addOpt("widgetThemeKey", Widget::widgetThemeKey, Widget::getWidgetThemeKeyOverride, WidgetThemeKey.CODEC, null) + .addOpt("widgetThemeKey", Widget::widgetThemeKey, Widget::getWidgetThemeKeyOverride, WidgetThemeKey.CODEC, + null) .addOpt("themeOverride", Widget::themeOverride, Widget::getThemeOverride, ITheme.REFERENCE_CODEC, null) - .addOpt("excludeAreaInRecipeViewer", Widget::excludeAreaInRecipeViewer, Widget::isExcludeAreaInRecipeViewer, Codec.BOOL, false) + .addOpt("excludeAreaInRecipeViewer", Widget::excludeAreaInRecipeViewer, Widget::isExcludeAreaInRecipeViewer, + Codec.BOOL, false) .addOpt("tooltip", Widget::setTooltip, Widget::getTooltip, RichTooltip.CODEC, null) .addFieldsOf(StandardResizer.COMPACT_CODEC, Widget::resizer) .addFieldOf(Area.CODEC, Widget::getArea, "margin") @@ -87,7 +91,8 @@ public class Widget> extends AbstractWidget implements IPosi .build(); // other - @Getter private boolean excludeAreaInRecipeViewer = false; + @Getter + private boolean excludeAreaInRecipeViewer = false; // sizing @Getter private BiConsumer transform; @@ -296,7 +301,8 @@ public void drawOverlay(ModularGuiContext context, WidgetThemeEntry widgetThe @Override public void drawForeground(ModularGuiContext context) { RichTooltip tooltip = getTooltip(); - if (tooltip != null && !context.getUISettings().drawTooltipExternally() && isHoveringFor(tooltip.showUpTimer())) { + if (tooltip != null && !context.getUISettings().drawTooltipExternally() && + isHoveringFor(tooltip.showUpTimer())) { tooltip.draw(context); } } @@ -408,7 +414,8 @@ protected WidgetTheme getActiveWidgetTheme(WidgetThemeEntry widgetTheme, bool } /** - * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise calls + * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise + * calls * {@link #getWidgetThemeEntryInternal(ITheme)} * * @param theme theme to get widget theme from @@ -423,7 +430,8 @@ public final WidgetThemeEntry getWidgetThemeEntry(ITheme theme) { } /** - * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise calls + * Returns the actual used widget theme entry. Uses {@link #widgetThemeKey(String)} if it has been set, otherwise + * calls * {@link #getWidgetThemeEntryInternal(ITheme)} * * @param theme theme to get widget theme entry from @@ -473,6 +481,7 @@ public W widgetThemeKey(WidgetThemeKey s) { /** * Sets an override theme to use for this widget and its children. * This will change the appearance of this widget according to the theme. + * * @param theme The theme to use. * @return this */ @@ -484,6 +493,7 @@ public W themeOverride(ITheme theme) { /** * Sets an override theme to use for this widget and its children. * This will change the appearance of this widget according to the theme. + * * @param theme The theme to use. * @return this */ @@ -496,7 +506,8 @@ public W themeOverride(String theme) { } /** - * Sets a shadow. Shadows are drawn before the background and don't actually have to be shadows. This doesn't effect theme backgrounds + * Sets a shadow. Shadows are drawn before the background and don't actually have to be shadows. This doesn't effect + * theme backgrounds * and doesn't change when hovered. * * @param shadow background to use. @@ -510,10 +521,12 @@ public W shadow(IDrawable... shadow) { /** * Sets a background. The theme background will be drawn before this override. *

- * NOTE: This will NOT disable the theme background. Disable it separately with {@link #disableThemeBackground(boolean)}. + * NOTE: This will NOT disable the theme background. Disable it separately with + * {@link #disableThemeBackground(boolean)}. *

* This method is meant for unique textures. For generic backgrounds please use themes. Also consider using - * {@link #overlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible while still overriding + * {@link #overlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible while + * still overriding * the widget theme. Background are drawn before the widget and overlays are drawn. * * @param background background to use. @@ -525,7 +538,8 @@ public W backgroundOverlay(IDrawable... background) { } /** - * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more information. + * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more + * information. * * @param background background * @return this @@ -548,20 +562,24 @@ public W overlay(IDrawable... overlay) { /** * Sets a hover background. The hover theme background will be drawn before this override. *

- * NOTE: This will NOT disable the hover theme background. Disable it separately with {@link #disableHoverThemeBackground(boolean)}. + * NOTE: This will NOT disable the hover theme background. Disable it separately with + * {@link #disableHoverThemeBackground(boolean)}. *

*

* This method is meant for unique textures. For generic backgrounds please use themes. Also consider using - * {@link #hoverOverlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible while still + * {@link #hoverOverlay(IDrawable...)} instead. Using {@link IDrawable#EMPTY} will make the background invisible + * while still * overriding the widget theme. Background are drawn before the widget and overlays are drawn. *

* Following argument special cases should be considered: *

    - *
  • {@code null} will fallback to {@link WidgetThemeEntry#hoverTheme()}
  • - *
  • {@link IDrawable#EMPTY} will make the hover background invisible
  • - *
  • {@link IDrawable#NONE} will use the normal background instead (which is also achieved using {@link #disableHoverBackground()}) - * (note that this won't disable the hover theme background)
  • - *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the method
  • + *
  • {@code null} will fallback to {@link WidgetThemeEntry#hoverTheme()}
  • + *
  • {@link IDrawable#EMPTY} will make the hover background invisible
  • + *
  • {@link IDrawable#NONE} will use the normal background instead (which is also achieved using + * {@link #disableHoverBackground()}) + * (note that this won't disable the hover theme background)
  • + *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the + * method
  • *
* * @param background hover background to use. @@ -573,7 +591,8 @@ public W hoverBackgroundOverlay(IDrawable... background) { } /** - * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more information. + * Sets a background and disables the theme background. See {@link #backgroundOverlay(IDrawable...)} for more + * information. * * @param background background * @return this @@ -589,9 +608,11 @@ public W hoverBackground(IDrawable... background) { *

* Following argument special cases should be considered: *

    - *
  • {@link IDrawable#EMPTY} will make the hover overlay invisible
  • - *
  • {@code null} and {@link IDrawable#NONE} will use the normal overlay instead (which is also achieved using {@link #disableHoverOverlay()})
  • - *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the method
  • + *
  • {@link IDrawable#EMPTY} will make the hover overlay invisible
  • + *
  • {@code null} and {@link IDrawable#NONE} will use the normal overlay instead (which is also achieved using + * {@link #disableHoverOverlay()})
  • + *
  • multiple drawables, will result in them being drawn on top of each other in the order they are passed to the + * method
  • *
* * @param overlay hover overlay to use. @@ -613,13 +634,21 @@ public W disableHoverThemeBackground(boolean b) { } // background setter for codec - private void setBackground(IDrawable d) {setBackground(d, true, false);} + private void setBackground(IDrawable d) { + setBackground(d, true, false); + } - private void setHoverBackground(IDrawable d) {setBackground(d, true, true);} + private void setHoverBackground(IDrawable d) { + setBackground(d, true, true); + } - private void setBackgroundOverlay(IDrawable d) {setBackground(d, false, false);} + private void setBackgroundOverlay(IDrawable d) { + setBackground(d, false, false); + } - private void setHoverBackgroundOverlay(IDrawable d) {setBackground(d, false, true);} + private void setHoverBackgroundOverlay(IDrawable d) { + setBackground(d, false, true); + } private void setBackground(IDrawable drawable, boolean disableTheme, boolean hover) { if (drawable != null) { @@ -768,7 +797,7 @@ public W onUpdateListener(Consumer listener, boolean merge) { return getThis(); } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) private void setOnUpdateListener(Consumer listener) { onUpdateListener(listener); } @@ -832,7 +861,7 @@ public W transform(BiConsumer transform) { return getThis(); } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) private void setTransform(BiConsumer listener) { transform(listener); } @@ -981,7 +1010,7 @@ public W name(String name) { * This can be used to further configure widgets in ways not directly allowed by the builder functions. *

* For example, adding a click action to a progress widget changes from this: - * {@snippet lang="java": + * {@snippet lang = "java": * ProgressWidget progressWidget = new ProgressWidget() * .value() * .texture(); @@ -995,19 +1024,19 @@ public W name(String name) { * //... * } * to this: - * {@snippet lang="java": - * parentWidget.child(new ProgressWidget() - * .value() - * .texture() - * .configure(w -> { - * w.listenGuiAction((IGuiAction.MousePressed) (ctx, button) -> { - * if (!ctx.isMouseAbove(w)) return false; - * //... - * return true; - * }); - * })) - * .child() - * //... + * {@snippet lang = "java": + * parentWidget.child(new ProgressWidget() + * .value() + * .texture() + * .configure(w -> { + * w.listenGuiAction((IGuiAction.MousePressed) (ctx, button) -> { + * if (!ctx.isMouseAbove(w)) return false; + * // ... + * return true; + * }); + * })) + * .child() + * // ... * } * * @param configurator the configuration function diff --git a/src/main/java/brachy/modularui/widget/WidgetTree.java b/src/main/java/brachy/modularui/widget/WidgetTree.java index 2576018c..0e8f6078 100644 --- a/src/main/java/brachy/modularui/widget/WidgetTree.java +++ b/src/main/java/brachy/modularui/widget/WidgetTree.java @@ -98,11 +98,13 @@ public static Optional findFirstWithNameOptional(IWidget parent, String * @return the first widget with matching name and class or null if none was found */ @SuppressWarnings("unchecked") - public static @Nullable T findFirstWithNameNullable(IWidget parent, String name, Class type) { + public static @Nullable T findFirstWithNameNullable(IWidget parent, String name, + Class type) { return foreachChildWithResult(parent, w -> w.isNameAndType(name, type) ? (T) w : null, true); } - public static Optional findFirstWithNameOptional(IWidget parent, String name, Class type) { + public static Optional findFirstWithNameOptional(IWidget parent, String name, + Class type) { return Optional.ofNullable(findFirstWithNameNullable(parent, name, type)); } @@ -217,7 +219,8 @@ public static void collectSyncValues(PanelSyncManager syncManager, ModularPanel< } @ApiStatus.Internal - public static void collectSyncValues(PanelSyncManager syncManager, String panelName, IWidget panel, boolean includePanel) { + public static void collectSyncValues(PanelSyncManager syncManager, String panelName, IWidget panel, + boolean includePanel) { MutableInt id = new MutableInt(0); String syncKey = ModularSyncManager.AUTO_SYNC_PREFIX + panelName; foreachChildBFS(panel, widget -> { @@ -233,7 +236,8 @@ public static void collectSyncValues(PanelSyncManager syncManager, String panelN public static int countUnregisteredSyncHandlers(PanelSyncManager syncManager, IWidget parent) { MutableInt count = new MutableInt(); foreachChildBFS(parent, widget -> { - if (widget instanceof ISynced synced && synced.isSynced() && !synced.getSyncHandler().isRegistered(syncManager)) { + if (widget instanceof ISynced synced && synced.isSynced() && + !synced.getSyncHandler().isRegistered(syncManager)) { count.increment(); } return true; diff --git a/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java b/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java index 0e4ccfd7..46ec5ee1 100755 --- a/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java +++ b/src/main/java/brachy/modularui/widget/scroll/HorizontalScrollData.java @@ -6,7 +6,6 @@ import brachy.modularui.screen.viewport.ModularGuiContext; import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.Color; -import brachy.modularui.utils.math.MathUtils; import net.minecraft.util.Mth; @@ -110,13 +109,15 @@ public void drawScrollShadow(ScrollArea area, ModularGuiContext context) { float prog = Mth.clamp(s / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawHorizontalGradientRect(context.getGraphics(), sp.getScrollPaddingLeft(), y, size, h, startColor, endColor); + GuiDraw.drawHorizontalGradientRect(context.getGraphics(), sp.getScrollPaddingLeft(), y, size, h, startColor, + endColor); } if (s < max) { float prog = Mth.clamp((max - s) / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawHorizontalGradientRect(context.getGraphics(), area.w() - size - sp.getScrollPaddingRight(), y, size, h, endColor, startColor); + GuiDraw.drawHorizontalGradientRect(context.getGraphics(), area.w() - size - sp.getScrollPaddingRight(), y, + size, h, endColor, startColor); } } } diff --git a/src/main/java/brachy/modularui/widget/scroll/ScrollData.java b/src/main/java/brachy/modularui/widget/scroll/ScrollData.java index 215bfaee..a8e174ab 100755 --- a/src/main/java/brachy/modularui/widget/scroll/ScrollData.java +++ b/src/main/java/brachy/modularui/widget/scroll/ScrollData.java @@ -253,7 +253,8 @@ public ScrollData texture(IDrawable drawable) { } @OnlyIn(Dist.CLIENT) - public abstract void drawScrollbar(ModularGuiContext context, ScrollArea area, WidgetTheme widgetTheme, IDrawable texture); + public abstract void drawScrollbar(ModularGuiContext context, ScrollArea area, WidgetTheme widgetTheme, + IDrawable texture); @OnlyIn(Dist.CLIENT) protected void drawScrollBar(ModularGuiContext context, int x, int y, int w, int h, WidgetTheme widgetTheme, diff --git a/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java b/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java index 1ef9f48b..03172993 100755 --- a/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java +++ b/src/main/java/brachy/modularui/widget/scroll/ScrollPadding.java @@ -13,10 +13,14 @@ public class ScrollPadding extends Box { public static final ScrollPadding SHARED = new ScrollPadding(); public static final ScrollPadding ZERO = new ScrollPadding(); - @Getter protected int scrollPaddingLeft; - @Getter protected int scrollPaddingTop; - @Getter protected int scrollPaddingRight; - @Getter protected int scrollPaddingBottom; + @Getter + protected int scrollPaddingLeft; + @Getter + protected int scrollPaddingTop; + @Getter + protected int scrollPaddingRight; + @Getter + protected int scrollPaddingBottom; public ScrollPadding scrollPaddingAll(int all) { return this.scrollPaddingAll(all, all); diff --git a/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java b/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java index 779d76f2..9e968adb 100755 --- a/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java +++ b/src/main/java/brachy/modularui/widget/scroll/VerticalScrollData.java @@ -6,7 +6,6 @@ import brachy.modularui.screen.viewport.ModularGuiContext; import brachy.modularui.theme.WidgetTheme; import brachy.modularui.utils.Color; -import brachy.modularui.utils.math.MathUtils; import net.minecraft.util.Mth; @@ -109,13 +108,15 @@ public void drawScrollShadow(ScrollArea area, ModularGuiContext context) { float prog = Mth.clamp(s / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, sp.getScrollPaddingTop(), w, size, startColor, endColor); + GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, sp.getScrollPaddingTop(), w, size, startColor, + endColor); } if (s < max) { float prog = Mth.clamp((max - s) / maxOpacityScroll, 0, 1); int startColor = Color.withAlpha(startColorFull, prog * 0.8f); int size = Math.min((int) (prog * maxShadowSize), maxShadowSizeLimit); - GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, area.h() - size - sp.getScrollPaddingBottom(), w, size, endColor, startColor); + GuiDraw.drawVerticalGradientRect(context.getGraphics(), x, area.h() - size - sp.getScrollPaddingBottom(), w, + size, endColor, startColor); } } } diff --git a/src/main/java/brachy/modularui/widget/sizer/Area.java b/src/main/java/brachy/modularui/widget/sizer/Area.java index dfd4fb55..ad0e4454 100644 --- a/src/main/java/brachy/modularui/widget/sizer/Area.java +++ b/src/main/java/brachy/modularui/widget/sizer/Area.java @@ -12,8 +12,8 @@ import net.minecraft.client.gui.navigation.ScreenRectangle; import net.minecraft.util.Mth; -import com.mojang.serialization.Codec; +import com.mojang.serialization.Codec; import lombok.Getter; import java.util.Objects; diff --git a/src/main/java/brachy/modularui/widget/sizer/Box.java b/src/main/java/brachy/modularui/widget/sizer/Box.java index f9d229cf..3b74f00f 100644 --- a/src/main/java/brachy/modularui/widget/sizer/Box.java +++ b/src/main/java/brachy/modularui/widget/sizer/Box.java @@ -6,7 +6,6 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import com.mojang.serialization.Codec; - import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; diff --git a/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java b/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java index d9e67a1b..8be7d884 100644 --- a/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java +++ b/src/main/java/brachy/modularui/widget/sizer/DimensionSizer.java @@ -8,7 +8,6 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import com.mojang.serialization.Codec; - import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -25,8 +24,10 @@ public class DimensionSizer { public static final MutableObjectCodec CODEC = MutableObjectCodec.builder(DimensionSizer.class) .baseCopy(sizer -> new DimensionSizer(sizer.resizer, sizer.axis)) - .addOpt("coverChildrenMinSize", DimensionSizer::setCoverChildrenMinSize, DimensionSizer::getCoverChildrenMinSize, Codec.INT, -1) - .addOpt("start", DimensionSizer::setStart, DimensionSizer::getStart, Unit.CODEC, Unit.ZERO).neverWriteDefault() + .addOpt("coverChildrenMinSize", DimensionSizer::setCoverChildrenMinSize, + DimensionSizer::getCoverChildrenMinSize, Codec.INT, -1) + .addOpt("start", DimensionSizer::setStart, DimensionSizer::getStart, Unit.CODEC, Unit.ZERO) + .neverWriteDefault() .addOpt("end", DimensionSizer::setEnd, DimensionSizer::getEnd, Unit.CODEC, Unit.ZERO).neverWriteDefault() .addOpt("size", DimensionSizer::setSize, DimensionSizer::getSize, Unit.CODEC, Unit.ZERO).neverWriteDefault() .build(); @@ -35,7 +36,8 @@ public class DimensionSizer { private final GuiAxis axis; private final Unit p1 = new Unit(), p2 = new Unit(); - @Getter(AccessLevel.PRIVATE) private Unit start, end, size; + @Getter(AccessLevel.PRIVATE) + private Unit start, end, size; private Unit next = p1; @Getter @@ -292,7 +294,7 @@ public int postApply(ResizeNode resizer, ResizeNode relativeTo, int p0, int p1) } else if (this.end != null) { p = calcPoint(this.end, s, parentSize, parentCalculated) - s; } else { - p = area.getRelativePoint(this.axis) + p0/* + area.getMargin().getStart(this.axis)*/; + p = area.getRelativePoint(this.axis) + p0/* + area.getMargin().getStart(this.axis) */; moveAmount = -p0; } area.setRelativePoint(this.axis, p); @@ -400,7 +402,9 @@ protected Unit getPoint() { public void detectConflictingConfiguration() { if (this.expanded && this.coverChildrenMinSize >= 0) { - ModularUI.LOGGER.warn("Resizer '{}' has expanded() and coverChildren() on {} axis. This conflicts and may cause layout issues.", this.resizer, this.axis); + ModularUI.LOGGER.warn( + "Resizer '{}' has expanded() and coverChildren() on {} axis. This conflicts and may cause layout issues.", + this.resizer, this.axis); } // TODO detect when this depends and all siblings depend on parent and parent depends on all children } diff --git a/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java b/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java index c0f5e049..160e55b3 100644 --- a/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java +++ b/src/main/java/brachy/modularui/widget/sizer/ResizeNode.java @@ -114,7 +114,8 @@ public void setDefaultParent(ResizeNode resizeNode) { } protected void setParentOverride(ResizeNode resizeNode) { - // ModularUI.LOGGER.info("Set override parent of {} to {}. Current: default: {}, override: {}", this, resizeNode, + // ModularUI.LOGGER.info("Set override parent of {} to {}. Current: default: {}, override: {}", this, + // resizeNode, // this.defaultParent, this.parentOverride); if (resizeNode == this) throw new IllegalArgumentException("Tried to set itself as parent override in " + this); if (removeFromParent(this.parentOverride, this.defaultParent, resizeNode)) return; diff --git a/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java b/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java index 87be52fa..d7d4562e 100644 --- a/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java +++ b/src/main/java/brachy/modularui/widget/sizer/StandardResizer.java @@ -14,7 +14,6 @@ import brachy.modularui.widgets.layout.IExpander; import com.mojang.serialization.Codec; - import lombok.AccessLevel; import lombok.Getter; import org.jetbrains.annotations.ApiStatus; @@ -36,7 +35,8 @@ public class StandardResizer extends WidgetResizeNode implements IPositioned COMPACT_CODEC = MutableObjectCodec.builder(StandardResizer.class) + public static final MutableObjectCodec COMPACT_CODEC = MutableObjectCodec + .builder(StandardResizer.class) .baseCopy(resizer -> new StandardResizer(resizer.getWidget())) .addOpt("expanded", StandardResizer::expanded, StandardResizer::isExpanded, Codec.BOOL, false) .addOpt("decoration", StandardResizer::decoration, StandardResizer::isDecoration, Codec.BOOL, false) @@ -50,10 +50,14 @@ public class StandardResizer extends WidgetResizeNode implements IPositioned children, boolea // if all children sizes depend on their parent, just use the min size as default w = this.x.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children width when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children width when all children depend on their parent and min size is 0!"); return false; } } @@ -293,7 +298,8 @@ protected boolean doCoverChildren(IWidget widget, List children, boolea // if all children sizes depend on their parent, just use the min size as default h = this.y.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children height when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children height when all children depend on their parent and min size is 0!"); return false; } } @@ -372,7 +378,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List x1 = Math.max(x1, area.rx + area.width + padding.right() + margin.right()); } } else if (coverByDefaultSizeX) { - withDefaultW = Math.max(withDefaultW, child.getDefaultWidth() + margin.horizontal() + padding.horizontal()); + withDefaultW = Math.max(withDefaultW, + child.getDefaultWidth() + margin.horizontal() + padding.horizontal()); } } @@ -388,7 +395,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List y1 = Math.max(y1, area.ry + area.height + padding.bottom() + margin.bottom()); } } else if (coverByDefaultSizeY) { - withDefaultH = Math.max(withDefaultH, child.getDefaultHeight() + margin.vertical() + padding.vertical()); + withDefaultH = Math.max(withDefaultH, + child.getDefaultHeight() + margin.vertical() + padding.vertical()); } } } @@ -398,7 +406,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List // if all children sizes depend on their parent, just use the min size as default w = this.x.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children width when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children width when all children depend on their parent and min size is 0!"); return; } } @@ -407,7 +416,8 @@ protected void coverChildrenForLayout(ILayoutWidget layout, IWidget widget, List // if all children sizes depend on their parent, just use the min size as default h = this.y.getCoverChildrenMinSize(); } else { - GuiError.throwNew(getWidget(), GuiError.Type.SIZING, "Can't cover children height when all children depend on their parent and min size is 0!"); + GuiError.throwNew(getWidget(), GuiError.Type.SIZING, + "Can't cover children height when all children depend on their parent and min size is 0!"); return; } } diff --git a/src/main/java/brachy/modularui/widget/sizer/Unit.java b/src/main/java/brachy/modularui/widget/sizer/Unit.java index 3fc937b1..c00a84e0 100644 --- a/src/main/java/brachy/modularui/widget/sizer/Unit.java +++ b/src/main/java/brachy/modularui/widget/sizer/Unit.java @@ -4,8 +4,8 @@ import brachy.modularui.utils.serialization.codec.MutableObjectCodec; import net.minecraft.util.StringRepresentable; -import com.mojang.serialization.Codec; +import com.mojang.serialization.Codec; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -179,7 +179,6 @@ public String getText(GuiAxis axis) { return axis.isHorizontal() ? this.xText : this.yText; } - @Override public @NotNull String getSerializedName() { return this.name; diff --git a/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java b/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java index 28471c35..49e1115a 100644 --- a/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java +++ b/src/main/java/brachy/modularui/widgets/AbstractCycleButtonWidget.java @@ -27,14 +27,17 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; -public class AbstractCycleButtonWidget> extends SingleChildWidget implements Interactable { +public class AbstractCycleButtonWidget> extends SingleChildWidget + implements Interactable { private static final State[] EMPTY = new State[0]; - @Getter private int stateCount = 0; + @Getter + private int stateCount = 0; private boolean explicitStateCount = false; private boolean hasCount = false; - @Getter private IIntValue intValue; + @Getter + private IIntValue intValue; private int lastValue = -1; private State[] states = EMPTY; protected IWidget fallbackChild = null; @@ -81,7 +84,9 @@ public State getOrCreateState(int index) { updateStateCount(index + 1, false); if (this.stateCount <= index) { if (this.explicitStateCount) { - throw new IllegalArgumentException("Could not get state %d of widget %s. The state count was explicitly set to %d.".formatted(index, this, this.stateCount)); + throw new IllegalArgumentException( + "Could not get state %d of widget %s. The state count was explicitly set to %d." + .formatted(index, this, this.stateCount)); } throw new IllegalStateException("For some reason less states are available then expected."); } diff --git a/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java b/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java index c55e9bc3..44dde45e 100644 --- a/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java +++ b/src/main/java/brachy/modularui/widgets/AbstractFluidDisplayWidget.java @@ -3,7 +3,6 @@ import brachy.modularui.api.ITheme; import brachy.modularui.drawable.GuiDraw; import brachy.modularui.integration.recipeviewer.RecipeSlotRole; -import brachy.modularui.integration.recipeviewer.entry.EntryList; import brachy.modularui.integration.recipeviewer.entry.fluid.FluidStackList; import brachy.modularui.integration.recipeviewer.handlers.IngredientProvider; import brachy.modularui.screen.viewport.ModularGuiContext; @@ -20,17 +19,21 @@ import lombok.Getter; import org.jetbrains.annotations.NotNull; -public abstract class AbstractFluidDisplayWidget> extends Widget implements IngredientProvider { +public abstract class AbstractFluidDisplayWidget> extends Widget + implements IngredientProvider { public static final String UNIT_BUCKET = "B"; public static final String UNIT_LITER = "L"; - @Getter private final Box contentPadding = new Box().all(1); + @Getter + private final Box contentPadding = new Box().all(1); private String unit = UNIT_BUCKET; - @Getter private SIPrefix baseUnitPrefix = SIPrefix.Milli; - @Getter private boolean flipLighterThanAir = true; - @Getter private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; - + @Getter + private SIPrefix baseUnitPrefix = SIPrefix.Milli; + @Getter + private boolean flipLighterThanAir = true; + @Getter + private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; protected AbstractFluidDisplayWidget() { size(18); @@ -63,7 +66,8 @@ public void drawOverlay(ModularGuiContext context, WidgetThemeEntry widgetThe super.drawOverlay(context, widgetTheme); FluidStack fluid = getFluidStack(); if (!fluid.isEmpty() && displayAmountText()) { - String s = NumberFormat.format(getBaseUnitAmount(fluid.getAmount()), NumberFormat.AMOUNT_TEXT) + getBaseUnit(); + String s = NumberFormat.format(getBaseUnitAmount(fluid.getAmount()), NumberFormat.AMOUNT_TEXT) + + getBaseUnit(); // mc doesn't consider the 1px border in item slots for amount text, but it looks weird when it touches the // left border, so we only apply padding there GuiDraw.drawScaledAlignedTextInBox(context, s, this.contentPadding.left(), 0, diff --git a/src/main/java/brachy/modularui/widgets/ButtonWidget.java b/src/main/java/brachy/modularui/widgets/ButtonWidget.java index b0fc13bd..ddce27dc 100644 --- a/src/main/java/brachy/modularui/widgets/ButtonWidget.java +++ b/src/main/java/brachy/modularui/widgets/ButtonWidget.java @@ -29,8 +29,10 @@ public static ButtonWidget panelCloseButton() { }); } - @Getter private boolean playClickSound = true; - @Getter private Runnable clickSound; + @Getter + private boolean playClickSound = true; + @Getter + private Runnable clickSound; private IGuiAction.MousePressed mousePressed; private IGuiAction.MouseReleased mouseReleased; private IGuiAction.MousePressed mouseTapped; diff --git a/src/main/java/brachy/modularui/widgets/CategoryList.java b/src/main/java/brachy/modularui/widgets/CategoryList.java index e1f4e8c2..2a1e3567 100644 --- a/src/main/java/brachy/modularui/widgets/CategoryList.java +++ b/src/main/java/brachy/modularui/widgets/CategoryList.java @@ -20,7 +20,8 @@ public class CategoryList extends AbstractParentWidget implements Interactable, ILayoutWidget { private final List subCategories = new ArrayList<>(); - @Getter private boolean expanded = false; + @Getter + private boolean expanded = false; private int totalHeight = 0; private IDrawable expandedOverlay; private IDrawable collapsedOverlay; diff --git a/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java b/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java index 43719ba6..bc46c7fa 100644 --- a/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java +++ b/src/main/java/brachy/modularui/widgets/ColorPickerDialog.java @@ -15,26 +15,32 @@ import brachy.modularui.widgets.layout.Flow; import brachy.modularui.widgets.textfield.TextFieldWidget; +import lombok.Getter; import org.jetbrains.annotations.Nullable; -import java.util.function.Consumer; import java.util.function.Supplier; -import lombok.Getter; public class ColorPickerDialog extends Dialog { private static final IDrawable handleBackground = new Rectangle().color(Color.WHITE.main); - @Getter private int color; - @Getter private int red; - @Getter private int green; - @Getter private int blue; - @Getter private double hue; - @Getter private double saturation; + @Getter + private int color; + @Getter + private int red; + @Getter + private int green; + @Getter + private int blue; + @Getter + private double hue; + @Getter + private double saturation; private double value; private int alpha; - @Getter private final boolean controlAlpha; + @Getter + private final boolean controlAlpha; private final Rectangle preview = new Rectangle(); private final Rectangle sliderBackgroundR = new Rectangle(); diff --git a/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java b/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java index 7174f806..2fe561c6 100755 --- a/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java +++ b/src/main/java/brachy/modularui/widgets/CycleButtonWidget.java @@ -9,10 +9,12 @@ import java.util.function.Consumer; /** - * A button which cycles between multiple states by clicking on it. Background, overlay and tooltip can be supplied perstate. + * A button which cycles between multiple states by clicking on it. Background, overlay and tooltip can be supplied + * perstate. *

* Note that you need to set the amount of states before setting any state backgrounds etc. The state count is - * automatically set, if the passed {@link IIntValue} is a {@link IEnumValue IEnumValue} or a {@link IBoolValue IBoolValue}. + * automatically set, if the passed {@link IIntValue} is a {@link IEnumValue IEnumValue} or a {@link IBoolValue + * IBoolValue}. *

* * @see ToggleButton diff --git a/src/main/java/brachy/modularui/widgets/Expandable.java b/src/main/java/brachy/modularui/widgets/Expandable.java index 96f1e101..2c35a23a 100644 --- a/src/main/java/brachy/modularui/widgets/Expandable.java +++ b/src/main/java/brachy/modularui/widgets/Expandable.java @@ -23,16 +23,23 @@ public class Expandable extends Widget implements Interactable, IViewport { - @Getter private IWidget normalView = new EmptyWidget(); - @Getter private IWidget expandedView = new EmptyWidget(); + @Getter + private IWidget normalView = new EmptyWidget(); + @Getter + private IWidget expandedView = new EmptyWidget(); private final List children = Arrays.asList(normalView, expandedView); private List currentChildren = children; - @Getter private boolean expanded = false; + @Getter + private boolean expanded = false; private Area areaSnapshot; - @Getter private Animator animator; - @Getter private BiConsumer stencilTransform; - @Getter private int animationDuration = 300; - @Getter private IInterpolation interpolation = Interpolation.SINE_OUT; + @Getter + private Animator animator; + @Getter + private BiConsumer stencilTransform; + @Getter + private int animationDuration = 300; + @Getter + private IInterpolation interpolation = Interpolation.SINE_OUT; public Expandable() { coverChildren(); diff --git a/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java b/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java index 4006ed51..2004542a 100644 --- a/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java +++ b/src/main/java/brachy/modularui/widgets/FluidDisplayWidget.java @@ -15,9 +15,12 @@ public class FluidDisplayWidget extends AbstractFluidDisplayWidget { - @Getter private IValue value; - @Getter private int capacity = 0; - @Getter private boolean displayAmount = true; + @Getter + private IValue value; + @Getter + private int capacity = 0; + @Getter + private boolean displayAmount = true; @Override public boolean isValidSyncOrValue(@NotNull ISyncOrValue syncOrValue) { diff --git a/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java b/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java index ad63f075..eb289611 100644 --- a/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java +++ b/src/main/java/brachy/modularui/widgets/ItemDisplayWidget.java @@ -20,9 +20,12 @@ public class ItemDisplayWidget extends Widget implements IngredientProvider { - @Getter private IValue value; - @Getter private boolean displayAmount = false; - @Getter private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; + @Getter + private IValue value; + @Getter + private boolean displayAmount = false; + @Getter + private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; public ItemDisplayWidget() { size(18); diff --git a/src/main/java/brachy/modularui/widgets/ListWidget.java b/src/main/java/brachy/modularui/widgets/ListWidget.java index 374de678..b0e884f6 100644 --- a/src/main/java/brachy/modularui/widgets/ListWidget.java +++ b/src/main/java/brachy/modularui/widgets/ListWidget.java @@ -33,14 +33,19 @@ * @param type of this widget */ public class ListWidget> extends AbstractScrollWidget - implements ILayoutWidget, IParentWidget { + implements ILayoutWidget, IParentWidget { - @Getter private ScrollData scrollData; - @Getter private IIcon childSeparator; + @Getter + private ScrollData scrollData; + @Getter + private IIcon childSeparator; private final IntList separatorPositions = new IntArrayList(); - @Getter private boolean collapseDisabledChildren = true; - @Getter private boolean wrapTight = false; - @Getter private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; + @Getter + private boolean collapseDisabledChildren = true; + @Getter + private boolean wrapTight = false; + @Getter + private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; private Unit mainAxisMaxSize; /** * Whether the children list should be laid out in reverse. @@ -302,8 +307,10 @@ public W collapseDisabledChildren() { } /** - * Sets if disabled children should be collapsed. This means that if a child changes enabled state, this widget gets notified and - * re-layouts its children. Children which are disabled will not be considered during layout, so that the list will not appear to have + * Sets if disabled children should be collapsed. This means that if a child changes enabled state, this widget gets + * notified and + * re-layouts its children. Children which are disabled will not be considered during layout, so that the list will + * not appear to have * empty spots. This is enabled by default on lists. * * @param doCollapse true if disabled children should be collapsed. diff --git a/src/main/java/brachy/modularui/widgets/PageButton.java b/src/main/java/brachy/modularui/widgets/PageButton.java index 0fee754d..a84d6096 100755 --- a/src/main/java/brachy/modularui/widgets/PageButton.java +++ b/src/main/java/brachy/modularui/widgets/PageButton.java @@ -15,10 +15,12 @@ public class PageButton extends Widget implements Interactable { - @Getter private final int index; + @Getter + private final int index; private final PagedWidget.Controller controller; private IDrawable inactiveTexture = null; - @Getter private boolean invert = false; + @Getter + private boolean invert = false; public PageButton(int index, PagedWidget.Controller controller) { this.index = index; diff --git a/src/main/java/brachy/modularui/widgets/PagedWidget.java b/src/main/java/brachy/modularui/widgets/PagedWidget.java index 41280263..e07fe4e9 100755 --- a/src/main/java/brachy/modularui/widgets/PagedWidget.java +++ b/src/main/java/brachy/modularui/widgets/PagedWidget.java @@ -14,11 +14,15 @@ public class PagedWidget> extends Widget { - @Getter private final List pages = new ArrayList<>(); - @Getter private IWidget currentPage; - @Getter private int currentPageIndex = 0; - - @Nullable private IntConsumer onPageChange; + @Getter + private final List pages = new ArrayList<>(); + @Getter + private IWidget currentPage; + @Getter + private int currentPageIndex = 0; + + @Nullable + private IntConsumer onPageChange; @Override public void afterInit() { diff --git a/src/main/java/brachy/modularui/widgets/RichTextWidget.java b/src/main/java/brachy/modularui/widgets/RichTextWidget.java index f4c7e670..cf290849 100755 --- a/src/main/java/brachy/modularui/widgets/RichTextWidget.java +++ b/src/main/java/brachy/modularui/widgets/RichTextWidget.java @@ -21,7 +21,8 @@ public class RichTextWidget extends Widget implements IRichTextB private final RichText text = new RichText(); private Consumer builder; private boolean dirty = false; - @Getter private boolean autoUpdate = false; + @Getter + private boolean autoUpdate = false; public void markDirty() { this.dirty = true; @@ -43,7 +44,8 @@ public void draw(ModularGuiContext context, WidgetThemeEntry widgetTheme) { @Override public void drawForeground(ModularGuiContext context) { super.drawForeground(context); - if (!context.getUISettings().drawTooltipExternally() && getHoveredElement(context) instanceof IHoverable hoverable) { + if (!context.getUISettings().drawTooltipExternally() && + getHoveredElement(context) instanceof IHoverable hoverable) { hoverable.onHover(); RichTooltip tooltip = hoverable.getTooltip(); if (tooltip != null) { diff --git a/src/main/java/brachy/modularui/widgets/SchemaWidget.java b/src/main/java/brachy/modularui/widgets/SchemaWidget.java index c6b0e9f1..dbe65b83 100755 --- a/src/main/java/brachy/modularui/widgets/SchemaWidget.java +++ b/src/main/java/brachy/modularui/widgets/SchemaWidget.java @@ -11,8 +11,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; -import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.InputConstants; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.joml.Vector3f; @@ -20,14 +20,22 @@ public class SchemaWidget extends Widget implements Interactable { - @Getter private final BaseSchemaRenderer schemaRenderer; - @Getter private boolean enableRotation = true; - @Getter private boolean enableTranslation = true; - @Getter private boolean enableScaling = true; - @Getter private float scale = 10f; - @Getter private float pitch = MathUtils.PI_QUART; - @Getter private float yaw = 0; - @Getter private final Vector3f offset = new Vector3f(); + @Getter + private final BaseSchemaRenderer schemaRenderer; + @Getter + private boolean enableRotation = true; + @Getter + private boolean enableTranslation = true; + @Getter + private boolean enableScaling = true; + @Getter + private float scale = 10f; + @Getter + private float pitch = MathUtils.PI_QUART; + @Getter + private float yaw = 0; + @Getter + private final Vector3f offset = new Vector3f(); public SchemaWidget(ISchema schema) { this(new BaseSchemaRenderer(schema)); diff --git a/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java b/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java index 3fd0a578..cccd70a0 100755 --- a/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java +++ b/src/main/java/brachy/modularui/widgets/ScrollingTextWidget.java @@ -17,10 +17,14 @@ public class ScrollingTextWidget extends TextWidget { private TextRenderer.Line line; - @Getter private float progress = 0; - @Getter private IAnimator animator; - @Getter private Animator forward; - @Getter private Animator backward; + @Getter + private float progress = 0; + @Getter + private IAnimator animator; + @Getter + private Animator forward; + @Getter + private Animator backward; private int speed = 15; diff --git a/src/main/java/brachy/modularui/widgets/SliderWidget.java b/src/main/java/brachy/modularui/widgets/SliderWidget.java index c1e51865..a4539752 100644 --- a/src/main/java/brachy/modularui/widgets/SliderWidget.java +++ b/src/main/java/brachy/modularui/widgets/SliderWidget.java @@ -27,17 +27,25 @@ @Accessors(chain = true) public class SliderWidget extends Widget implements Interactable { - @Getter private IDoubleValue doubleValue; + @Getter + private IDoubleValue doubleValue; private IDrawable stopperDrawable = new Rectangle().color(Color.withAlpha(Color.WHITE.main, 0.4f)); private IDrawable handleDrawable = GuiTextures.BUTTON_CLEAN; - @Getter private GuiAxis axis = GuiAxis.X; - @Getter private DoubleList stopper; - @Getter private int stopperWidth = 2, stopperHeight = 4; + @Getter + private GuiAxis axis = GuiAxis.X; + @Getter + private DoubleList stopper; + @Getter + private int stopperWidth = 2, stopperHeight = 4; private final Unit sliderWidth = new Unit(), sliderHeight = new Unit(); - @Getter private final Area sliderArea = new Area(); - @Getter private double min, max; - @Getter private double each = 0; - @Getter private boolean dragging = false; + @Getter + private final Area sliderArea = new Area(); + @Getter + private double min, max; + @Getter + private double each = 0; + @Getter + private boolean dragging = false; private double cache = Double.MIN_VALUE; diff --git a/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java b/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java index c1edfadb..dae33409 100644 --- a/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java +++ b/src/main/java/brachy/modularui/widgets/SlotGroupWidget.java @@ -76,8 +76,10 @@ public static SlotGroupWidget rect(int w, int h, IntFunction slotCreato return slots.size(w * 18, h * 18); } - @Getter private String slotGroupName; - @Getter private SlotGroup slotGroup; + @Getter + private String slotGroupName; + @Getter + private SlotGroup slotGroup; private boolean sortButtonsAdded = false; private Consumer sortButtonsEditor; diff --git a/src/main/java/brachy/modularui/widgets/SortButtons.java b/src/main/java/brachy/modularui/widgets/SortButtons.java index 128de6a0..84322154 100644 --- a/src/main/java/brachy/modularui/widgets/SortButtons.java +++ b/src/main/java/brachy/modularui/widgets/SortButtons.java @@ -38,8 +38,11 @@ public class SortButtons extends Widget { } } - @Getter private String slotGroupName; - @Getter @Setter private SlotGroup slotGroup; + @Getter + private String slotGroupName; + @Getter + @Setter + private SlotGroup slotGroup; private boolean horizontal = true; private final ButtonWidget sortButton = new ButtonWidget<>(); diff --git a/src/main/java/brachy/modularui/widgets/TextWidget.java b/src/main/java/brachy/modularui/widgets/TextWidget.java index f5e71b0b..081030a0 100644 --- a/src/main/java/brachy/modularui/widgets/TextWidget.java +++ b/src/main/java/brachy/modularui/widgets/TextWidget.java @@ -23,12 +23,18 @@ public class TextWidget> extends Widget { - @Getter private Component key; - @Getter private Alignment alignment = Alignment.CenterLeft; - @Getter private IntSupplier color = null; - @Getter private Boolean textShadow = null; - @Getter private float scale = 1f; - @Getter private int maxWidth = -1; + @Getter + private Component key; + @Getter + private Alignment alignment = Alignment.CenterLeft; + @Getter + private IntSupplier color = null; + @Getter + private Boolean textShadow = null; + @Getter + private float scale = 1f; + @Getter + private int maxWidth = -1; private String lastText; private @Nullable Supplier keySupplier; @@ -102,7 +108,8 @@ private TextRenderer simulate(float maxWidth) { renderer.setPos(padding.left(), padding.top()); renderer.setScale(this.scale); renderer.setSimulate(true); - // Don't update the key here, otherwise an infinite loop of checkComponentUpdated -> simulate -> checkComponentUpdated occurs + // Don't update the key here, otherwise an infinite loop of checkComponentUpdated -> simulate -> + // checkComponentUpdated occurs renderer.draw(null, this.key); renderer.setSimulate(false); return renderer; @@ -184,7 +191,7 @@ public W shadow(@Nullable Boolean shadow) { public W style(ChatFormatting formatting) { // TODO - //this.key.style(formatting); + // this.key.style(formatting); return getThis(); } diff --git a/src/main/java/brachy/modularui/widgets/ToggleButton.java b/src/main/java/brachy/modularui/widgets/ToggleButton.java index 759d7ef8..7c8ab5f0 100644 --- a/src/main/java/brachy/modularui/widgets/ToggleButton.java +++ b/src/main/java/brachy/modularui/widgets/ToggleButton.java @@ -9,7 +9,6 @@ import brachy.modularui.theme.SelectableTheme; import brachy.modularui.theme.WidgetTheme; import brachy.modularui.theme.WidgetThemeEntry; - import brachy.modularui.value.BoolValue; import lombok.Getter; @@ -54,7 +53,8 @@ public ToggleButton value(IBoolValue boolValue) { } public ToggleButton valueWrapped(IIntValue intValue, int trueValue) { - return value(new BoolValue.Dynamic(() -> intValue.getIntValue() == trueValue, v -> intValue.setIntValue(trueValue))); + return value( + new BoolValue.Dynamic(() -> intValue.getIntValue() == trueValue, v -> intValue.setIntValue(trueValue))); } public ToggleButton background(boolean selected, IDrawable drawable) { diff --git a/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java b/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java index aaec6bac..04f340b6 100644 --- a/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java +++ b/src/main/java/brachy/modularui/widgets/dynamic/DynamicHandler.java @@ -43,4 +43,3 @@ public DynamicHandler widgetProvider(Supplier widgetProvider) { return this; } } - diff --git a/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java b/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java index 23db515d..1039e1d7 100644 --- a/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java +++ b/src/main/java/brachy/modularui/widgets/dynamic/DynamicWidget.java @@ -16,8 +16,10 @@ /** * A widget which can update its child based on a function in {@link DynamicSyncHandler}. * Such a sync handler must be supplied or else this widget has no effect. - * The dynamic child can be a widget tree of any size which can also contain {@link SyncHandler}s. These sync handlers MUST be registered - * via a variant of {@link brachy.modularui.value.sync.PanelSyncManager#getOrCreateSyncHandler(String, Class, Supplier)}. + * The dynamic child can be a widget tree of any size which can also contain {@link SyncHandler}s. These sync handlers + * MUST be registered + * via a variant of + * {@link brachy.modularui.value.sync.PanelSyncManager#getOrCreateSyncHandler(String, Class, Supplier)}. * * @param type of this widget */ diff --git a/src/main/java/brachy/modularui/widgets/layout/Flow.java b/src/main/java/brachy/modularui/widgets/layout/Flow.java index 77969812..3dc3b3b1 100644 --- a/src/main/java/brachy/modularui/widgets/layout/Flow.java +++ b/src/main/java/brachy/modularui/widgets/layout/Flow.java @@ -35,30 +35,38 @@ public static Flow col() { /** * The main axis on which to align children. */ - @Getter private final GuiAxis axis; + @Getter + private final GuiAxis axis; /** * How the children should be laid out on the main axis. */ - @Getter private Alignment.MainAxis mainAxisAlignment = Alignment.MainAxis.START; + @Getter + private Alignment.MainAxis mainAxisAlignment = Alignment.MainAxis.START; /** * How the children should be laid out on the cross axis. */ - @Getter private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; + @Getter + private Alignment.CrossAxis crossAxisAlignment = Alignment.CrossAxis.CENTER; /** * Additional space between each child on main axis. * Does not work with {@link Alignment.MainAxis#SPACE_BETWEEN} and {@link Alignment.MainAxis#SPACE_AROUND}. */ - @Getter private int childPadding = 0; - @Getter private int crossAxisChildPadding = 0; + @Getter + private int childPadding = 0; + @Getter + private int crossAxisChildPadding = 0; /** * Whether disabled child widgets should be collapsed for display. */ - @Getter private boolean collapseDisabledChildren = false; + @Getter + private boolean collapseDisabledChildren = false; /** * Whether the children list should be laid out in reverse order */ - @Getter private boolean reverseLayout = false; - @Getter private boolean wrap = false; + @Getter + private boolean reverseLayout = false; + @Getter + private boolean wrap = false; private final List ignoredWidgets = new ArrayList<>(); private final List layoutWidgets = new ArrayList<>(); diff --git a/src/main/java/brachy/modularui/widgets/layout/Grid.java b/src/main/java/brachy/modularui/widgets/layout/Grid.java index 84a2856c..8bf30622 100755 --- a/src/main/java/brachy/modularui/widgets/layout/Grid.java +++ b/src/main/java/brachy/modularui/widgets/layout/Grid.java @@ -28,11 +28,15 @@ public class Grid extends AbstractScrollWidget implements ILayoutWidget, IParentWidget { private final List> matrix = new ArrayList<>(); - @Getter private final Box minElementMargin = new Box(); - @Getter private int minRowHeight = 5, minColWidth = 5; - @Getter private Alignment alignment = Alignment.Center; + @Getter + private final Box minElementMargin = new Box(); + @Getter + private int minRowHeight = 5, minColWidth = 5; + @Getter + private Alignment alignment = Alignment.Center; private boolean dirty = false, unsanitized = false; - @Getter private boolean collapseDisabledChildren = false; + @Getter + private boolean collapseDisabledChildren = false; public Grid() { super(null, null); @@ -353,7 +357,8 @@ public Grid collapseDisabledChildren() { * * @param width number of elements in each row * @param height number of elements in each column - * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). Can return null. + * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). + * Can return null. * @return this */ public Grid gridOfWidthHeight(int width, int height, GridPosMapper widgetCreator) { @@ -365,7 +370,8 @@ public Grid gridOfWidthHeight(int width, int height, GridPos * * @param size total number of elements (width * height) * @param height number of elements in each column - * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). Can return null. + * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). + * Can return null. * @return this */ public Grid gridOfSizeHeight(int size, int height, GridPosMapper widgetCreator) { @@ -377,7 +383,8 @@ public Grid gridOfSizeHeight(int size, int height, GridPosMa * * @param size total number of elements (width * height) * @param width number of elements in each row - * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). Can return null. + * @param widgetCreator A function that maps each pos to a widget. The arguments are (xIndex, yIndex, totalIndex). + * Can return null. * @return this */ public Grid gridOfSizeWidth(int size, int width, GridPosMapper widgetCreator) { @@ -388,12 +395,14 @@ public Grid gridOfSizeWidth(int size, int width, GridPosMapp * Creates a grid of widgets with a given grid of any type. * * @param matrix elements of any type - * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, totalIndex, element). Can return null. + * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, totalIndex, + * element). Can return null. * @param type of elements * @param widget type * @return this */ - public Grid gridOfElements(Iterable> matrix, GridPosElementMapper widgetCreator) { + public Grid gridOfElements(Iterable> matrix, + GridPosElementMapper widgetCreator) { return grid(createGridOfElements(matrix, widgetCreator)); } @@ -414,16 +423,19 @@ public Grid gridOf(int width, Iterable list) { * * @param width number of elements in each row * @param list elements of any type - * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, listIndex, element). Can return null. + * @param widgetCreator A mapper to map each element to a widget. The arguments are (xIndex, yIndex, listIndex, + * element). Can return null. * @param type of elements * @param widget type * @return this */ - public Grid gridOfWidthElements(int width, Iterable list, GridPosElementMapper widgetCreator) { + public Grid gridOfWidthElements(int width, Iterable list, + GridPosElementMapper widgetCreator) { return grid(createGridOfWidthElements(width, list, widgetCreator)); } - public static List> createGridOfElements(Iterable> matrix, GridPosElementMapper widgetCreator) { + public static List> createGridOfElements(Iterable> matrix, + GridPosElementMapper widgetCreator) { List> widgetMatrix = new ArrayList<>(); Iterator> colIt = matrix.iterator(); int r = 0, i = 0; @@ -442,7 +454,9 @@ public static List> createGridOfElements(Iterable return widgetMatrix; } - public static List> createGridOfWidthElements(int width, Iterable list, GridPosElementMapper widgetCreator) { + public static List> createGridOfWidthElements(int width, Iterable list, + GridPosElementMapper widgetCreator) { width = Math.max(width, 1); List> widgetMatrix = new ArrayList<>(); Iterator it = list.iterator(); @@ -462,7 +476,8 @@ public static List> createGridOfWidthElements(int return widgetMatrix; } - public static List> createGridOfWidthHeight(int width, int height, GridPosMapper widgetCreator) { + public static List> createGridOfWidthHeight(int width, int height, + GridPosMapper widgetCreator) { height = Math.max(height, 1); width = Math.max(width, 1); List> matrix = new ArrayList<>(); @@ -476,11 +491,13 @@ public static List> createGridOfWidthHeight(int widt return matrix; } - public static List> createGridOfSizeHeight(int size, int height, GridPosMapper widgetCreator) { + public static List> createGridOfSizeHeight(int size, int height, + GridPosMapper widgetCreator) { return createGridOfWidthHeight(calcSize(size, height), height, widgetCreator); } - public static List> createGridOfSizeWidth(int size, int width, GridPosMapper widgetCreator) { + public static List> createGridOfSizeWidth(int size, int width, + GridPosMapper widgetCreator) { return createGridOfWidthHeight(width, calcSize(size, width), widgetCreator); } @@ -489,7 +506,8 @@ private static int calcSize(int totalSize, int otherSize) { } /** - * Ensures that every row in the matrix has the same size by appending null values to rows with fewer elements than the longest row. + * Ensures that every row in the matrix has the same size by appending null values to rows with fewer elements than + * the longest row. */ private void sanitizeMatrix() { if (!this.unsanitized) return; @@ -509,7 +527,8 @@ private static void foreachRow(Iterable row, Consumer consumer row.forEach(consumer); } - private static void foreachGrid(Iterable> grid, Consumer consumer) { + private static void foreachGrid(Iterable> grid, + Consumer consumer) { for (Iterable row : grid) { row.forEach(consumer); } diff --git a/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java b/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java index 7fc98ed2..660aa797 100644 --- a/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java +++ b/src/main/java/brachy/modularui/widgets/menu/AbstractMenuButton.java @@ -28,7 +28,8 @@ * * @param type of this widget */ -public abstract class AbstractMenuButton> extends Widget implements IMenuPart, Interactable { +public abstract class AbstractMenuButton> extends Widget + implements IMenuPart, Interactable { /** * The general direction where the menu will be opened. This is just a shortcut to standard resizer calls. @@ -52,11 +53,13 @@ public abstract class AbstractMenuButton> extend /** * true if the menu is currently open (soft or hard) */ - @Getter private boolean open; + @Getter + private boolean open; /** * true if the menu is currently soft open (opened by hovering) */ - @Getter private boolean softOpen; // state, soft means opened by hovering + @Getter + private boolean softOpen; // state, soft means opened by hovering private IPanelHandler panelHandler; private final String panelName; diff --git a/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java b/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java index cbe6cf52..902d2854 100644 --- a/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java +++ b/src/main/java/brachy/modularui/widgets/menu/MenuPanel.java @@ -45,7 +45,7 @@ public boolean closeOnOutOfBoundsClick() { return true; } - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public void closeAllMenus(boolean soft, boolean requireNoHover) { // need to collect menus first instead of closing while iterating to avoid CME List menus = WidgetTree.flatListByType(this, Menu.class); diff --git a/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java b/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java index 505eab1b..aa20a7e3 100755 --- a/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java +++ b/src/main/java/brachy/modularui/widgets/slot/CraftingContainerWrapper.java @@ -14,7 +14,8 @@ /** * A crafting inventory that wraps a {@link IItemHandlerModifiable}. * This inventory creates a content list which is used here to detect changes from the item handler. - * This is required as interacting with a slot will update the content, but will not notify the container to check for new recipes. + * This is required as interacting with a slot will update the content, but will not notify the container to check for + * new recipes. */ public class CraftingContainerWrapper extends TransientCraftingContainer { diff --git a/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java b/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java index 6723dad6..0abcf191 100644 --- a/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/FluidSlot.java @@ -12,23 +12,22 @@ import brachy.modularui.screen.viewport.ModularGuiContext; import brachy.modularui.theme.SlotTheme; import brachy.modularui.theme.WidgetThemeEntry; -import brachy.modularui.utils.handlers.fluid.EmptyFluidTank; -import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; import brachy.modularui.utils.LangUtil; import brachy.modularui.utils.MouseData; +import brachy.modularui.utils.handlers.fluid.EmptyFluidTank; +import brachy.modularui.utils.handlers.fluid.IMultiTankFluidHandler; import brachy.modularui.value.sync.FluidSlotSyncHandler; import brachy.modularui.widgets.AbstractFluidDisplayWidget; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.world.level.material.Fluids; import net.neoforged.neoforge.capabilities.Capabilities; import net.neoforged.neoforge.common.SoundActions; import net.neoforged.neoforge.fluids.FluidStack; import net.neoforged.neoforge.fluids.IFluidTank; -import net.neoforged.neoforge.fluids.capability.templates.FluidTank; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import lombok.experimental.Accessors; import org.jetbrains.annotations.NotNull; @@ -38,7 +37,7 @@ @Accessors(fluent = true, chain = true) public class FluidSlot extends AbstractFluidDisplayWidget - implements Interactable, GhostIngredientSlot, IngredientProvider { + implements Interactable, GhostIngredientSlot, IngredientProvider { public static final int DEFAULT_SIZE = 18; public static final String UNIT_BUCKET = "B"; @@ -52,7 +51,8 @@ public class FluidSlot extends AbstractFluidDisplayWidget private FluidSlotSyncHandler syncHandler; - @Getter private boolean alwaysShowFull = true; + @Getter + private boolean alwaysShowFull = true; public FluidSlot() { tooltip().autoUpdate(true); diff --git a/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java b/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java index 67fff989..67e752e8 100755 --- a/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java +++ b/src/main/java/brachy/modularui/widgets/slot/IOnSlotChanged.java @@ -12,11 +12,11 @@ public interface IOnSlotChanged { /** * Called when an item stack in a {@link ModularSlot} changes. * - * @param oldStack the previous item in the slot - * @param newStack the item that is now in the slot - * @param client true if this function is currently called on client side - * @param init if this is the first sync call after opening the GUI. Doe not necessarily that this slot - * changed + * @param oldStack the previous item in the slot + * @param newStack the item that is now in the slot + * @param client true if this function is currently called on client side + * @param init if this is the first sync call after opening the GUI. Doe not necessarily that this slot + * changed */ void onChange(ItemStack oldStack, ItemStack newStack, boolean client, boolean init); } diff --git a/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java b/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java index a0e57bd8..a1a38300 100644 --- a/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/ItemSlot.java @@ -25,12 +25,12 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.neoforge.items.IItemHandlerModifiable; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.NotNull; @@ -42,7 +42,8 @@ public class ItemSlot extends Widget implements IVanillaSlot, Interact public static final int SIZE = 18; - @Getter private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; + @Getter + private RecipeSlotRole recipeRole = RecipeSlotRole.RENDER_ONLY; public static ItemSlot create(boolean phantom) { return phantom ? new PhantomItemSlot() : new ItemSlot(); @@ -113,7 +114,8 @@ protected void drawOverlay(ModularGuiContext context) { @Override public void drawForeground(ModularGuiContext context) { RichTooltip tooltip = getTooltip(); - if (tooltip != null && !context.getUISettings().drawTooltipExternally() && isHoveringFor(tooltip.showUpTimer())) { + if (tooltip != null && !context.getUISettings().drawTooltipExternally() && + isHoveringFor(tooltip.showUpTimer())) { tooltip.draw(context, getSlot().getItem()); } } @@ -241,7 +243,8 @@ private void drawSlot(ModularGuiContext context, ModularSlot slot) { String format = null; if (!getSyncHandler().isPhantom()) { - if (slot == acc.getClickedSlot() && !acc.getDraggingItem().isEmpty() && acc.getIsSplittingStack() && !slotStack.isEmpty()) { + if (slot == acc.getClickedSlot() && !acc.getDraggingItem().isEmpty() && acc.getIsSplittingStack() && + !slotStack.isEmpty()) { slotStack = slotStack.copy(); slotStack.setCount(slotStack.getCount() / 2); } else if (acc.getIsQuickCrafting() && acc.getQuickCraftSlots().contains(slot) && !carried.isEmpty()) { @@ -249,13 +252,15 @@ private void drawSlot(ModularGuiContext context, ModularSlot slot) { return; } - if (AbstractContainerMenu.canItemQuickReplace(slot, carried, true) && getScreen().getContainer().canDragTo(slot)) { + if (AbstractContainerMenu.canItemQuickReplace(slot, carried, true) && + getScreen().getContainer().canDragTo(slot)) { slotStack = carried.copy(); isDragPreview = true; int maxSize = Math.min(slotStack.getMaxStackSize(), slot.getMaxStackSize(slotStack)); amount = slot.getItem().getCount(); - amount += AbstractContainerMenu.getQuickCraftPlaceCount(acc.getQuickCraftSlots(), acc.getQuickCraftingType(), slotStack); + amount += AbstractContainerMenu.getQuickCraftPlaceCount(acc.getQuickCraftSlots(), + acc.getQuickCraftingType(), slotStack); if (amount > maxSize) { amount = maxSize; format = ChatFormatting.YELLOW.toString(); diff --git a/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java b/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java index 840a9822..3417b8c0 100755 --- a/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/ModularCraftingSlot.java @@ -3,12 +3,10 @@ import net.minecraft.core.NonNullList; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.inventory.RecipeCraftingHolder; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; -import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.GameRules; @@ -26,9 +24,11 @@ /** * An output slot for crafting recipes for modular UIs. For input slots use regular {@link ModularSlot ModularSlots}. * The implementation is mostly copied from {@link net.minecraft.world.inventory.ResultSlot ResultSlot}. - * To use this, you must call {@link #inputInventory(IItemHandlerModifiable, int)} or {@link #inputInventory(IItemHandlerModifiable)}. + * To use this, you must call {@link #inputInventory(IItemHandlerModifiable, int)} or + * {@link #inputInventory(IItemHandlerModifiable)}. * If the grid has any other size than 3x3, you also need to call {@link #gridSize(int, int)}. - * It is required that all input slots use the same {@link IItemHandlerModifiable}. Additionally, all input slots and this output slot, MUST + * It is required that all input slots use the same {@link IItemHandlerModifiable}. Additionally, all input slots and + * this output slot, MUST * be in the same slot group. */ @SuppressWarnings("unused") @@ -63,7 +63,8 @@ public ModularCraftingSlot gridSize(int columns, int rows) { } /** - * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from left to right, + * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from + * left to right, * top to bottom. For a 3x3 grid it would look like this: *

* 0 1 2
@@ -80,7 +81,8 @@ public ModularCraftingSlot inputInventory(IItemHandlerModifiable inputInventory) } /** - * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from left to right, + * Mandatory setter for the input inventory. The input inventory must contain the slot indices consecutively from + * left to right, * top to bottom. For a 3x3 grid with starting index 0 it would look like this: *

* 0 1 2
@@ -103,10 +105,12 @@ public ModularCraftingSlot inputInventory(IItemHandlerModifiable inputInventory, public CraftingContainerWrapper getCraftSlots() { if (this.craftSlots == null) { if (this.inputInventory == null) { - throw new IllegalStateException("The crafting inventory of the crafting slot has not been initialised. " + - "Call inputInventory() with appropriate arguments and optionally gridSize()."); + throw new IllegalStateException( + "The crafting inventory of the crafting slot has not been initialised. " + + "Call inputInventory() with appropriate arguments and optionally gridSize()."); } - this.craftSlots = new CraftingContainerWrapper(this, this.cols, this.rows, this.inputInventory, this.inputStartIndex); + this.craftSlots = new CraftingContainerWrapper(this, this.cols, this.rows, this.inputInventory, + this.inputStartIndex); } return this.craftSlots; } @@ -238,7 +242,8 @@ protected void updateCraftResult(Slot slot) { set(result); } - protected boolean setRecipeUsed(@Nullable Object possibleRecipeHolder, ServerPlayer player, RecipeHolder recipe) { + protected boolean setRecipeUsed(@Nullable Object possibleRecipeHolder, ServerPlayer player, + RecipeHolder recipe) { if (!recipe.value().isSpecial() && player.level().getGameRules().getBoolean(GameRules.RULE_LIMITED_CRAFTING) && !player.getRecipeBook().contains(recipe)) { return false; diff --git a/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java b/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java index bff8aba5..280a5d8f 100644 --- a/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java +++ b/src/main/java/brachy/modularui/widgets/slot/ModularSlot.java @@ -1,7 +1,7 @@ package brachy.modularui.widgets.slot; -import brachy.modularui.core.mixins.common.SlotAccessor; import brachy.modularui.core.mixins.common.CombinedInvWrapperAccessor; +import brachy.modularui.core.mixins.common.SlotAccessor; import brachy.modularui.value.sync.ItemSlotSyncHandler; import net.minecraft.resources.ResourceLocation; @@ -9,7 +9,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import com.mojang.datafixers.util.Pair; import net.neoforged.neoforge.items.IItemHandler; import net.neoforged.neoforge.items.IItemHandlerModifiable; import net.neoforged.neoforge.items.SlotItemHandler; @@ -18,6 +17,7 @@ import net.neoforged.neoforge.items.wrapper.PlayerMainInvWrapper; import net.neoforged.neoforge.items.wrapper.PlayerOffhandInvWrapper; +import com.mojang.datafixers.util.Pair; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.ApiStatus; @@ -39,10 +39,12 @@ public class ModularSlot extends SlotItemHandler { slot -> Objects.requireNonNull(slot.getSlotGroup()).getShiftClickPriority()); @Getter - @Setter(onMethod_ = {@ApiStatus.Internal}) + @Setter(onMethod_ = { @ApiStatus.Internal }) private boolean enabled = true; - @Getter private boolean canTake = true, canPut = true, canDragInto = true; - @Getter private Predicate filter = stack -> true; + @Getter + private boolean canTake = true, canPut = true, canDragInto = true; + @Getter + private Predicate filter = stack -> true; private IOnSlotChanged changeListener = IOnSlotChanged.DEFAULT; @Getter private boolean ignoreMaxStackSize = false; @@ -176,7 +178,8 @@ protected Player getPlayer() { @Override public boolean isSameInventory(@NotNull Slot other) { - return other instanceof SlotItemHandler slotItemHandler && slotItemHandler.getItemHandler() == this.getItemHandler(); + return other instanceof SlotItemHandler slotItemHandler && + slotItemHandler.getItemHandler() == this.getItemHandler(); } /** @@ -327,8 +330,7 @@ public static Player getPlayerFromInventorySlot(SlotItemHandler slot) { case PlayerArmorInvWrapper wrapper -> { return wrapper.getInventoryPlayer().player; } - default -> { - } + default -> {} } return null; } diff --git a/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java b/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java index 3aad273e..00b42eed 100644 --- a/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java +++ b/src/main/java/brachy/modularui/widgets/textfield/BaseTextFieldWidget.java @@ -17,8 +17,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; -import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.InputConstants; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.lwjgl.glfw.GLFW; @@ -33,7 +33,7 @@ * The base of a text input widget. Handles mouse/InputConstants input and rendering. */ public class BaseTextFieldWidget> extends AbstractScrollWidget - implements IFocusedWidget { + implements IFocusedWidget { public static final DecimalFormat format = new DecimalFormat("###.###"); @@ -57,15 +57,21 @@ public class BaseTextFieldWidget> extends Abstr @Getter protected List lastText; protected int scrollOffset = 0; - @Getter protected float scale = 1f; - @Getter protected boolean focusOnGuiOpen; + @Getter + protected float scale = 1f; + @Getter + protected boolean focusOnGuiOpen; private int cursorTimer; protected long lastClickTime = 0; - @Getter protected Integer textColor; - @Getter protected Integer markedColor; - @Getter protected Component hintText = null; - @Getter protected Integer hintTextColor; + @Getter + protected Integer textColor; + @Getter + protected Integer markedColor; + @Getter + protected Component hintText = null; + @Getter + protected Integer hintTextColor; public BaseTextFieldWidget() { super(new HorizontalScrollData(false, 4), null); diff --git a/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java b/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java index 3a67c5eb..5a198dbc 100755 --- a/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java +++ b/src/main/java/brachy/modularui/widgets/textfield/TextFieldRenderer.java @@ -9,10 +9,10 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.util.FormattedCharSequence; -import com.mojang.blaze3d.systems.RenderSystem; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import com.mojang.blaze3d.systems.RenderSystem; import lombok.Setter; import org.apache.commons.lang3.mutable.MutableFloat; import org.apache.commons.lang3.mutable.MutableInt; diff --git a/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java b/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java index c5ba55e7..7025fb39 100644 --- a/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java +++ b/src/main/java/brachy/modularui/widgets/textfield/TextFieldWidget.java @@ -39,14 +39,21 @@ @Accessors(chain = true) public class TextFieldWidget extends BaseTextFieldWidget { - @Getter private IStringValue stringValue; + @Getter + private IStringValue stringValue; private Function validator = val -> val; - @Getter private boolean numbers = false; - @Getter private String mathFailMessage = null; - @Getter private double defaultNumber = 0; - @Getter private boolean tooltipOverride = false; - @Getter private boolean autoUpdateOnChange = false; - @Getter private boolean acceptsExpression = true; + @Getter + private boolean numbers = false; + @Getter + private String mathFailMessage = null; + @Getter + private double defaultNumber = 0; + @Getter + private boolean tooltipOverride = false; + @Getter + private boolean autoUpdateOnChange = false; + @Getter + private boolean acceptsExpression = true; public double parse(String num) { if (!this.acceptsExpression) { @@ -115,7 +122,8 @@ public void onUpdate() { @Override public void drawForeground(ModularGuiContext context) { if (hasTooltip() && !context.getUISettings().drawTooltipExternally() && - (tooltipOverride || getScrollData().isScrollBarActive(getScrollArea())) && isHoveringFor(getTooltip().showUpTimer())) { + (tooltipOverride || getScrollData().isScrollBarActive(getScrollArea())) && + isHoveringFor(getTooltip().showUpTimer())) { getTooltip().draw(getContext()); } } @@ -159,7 +167,8 @@ protected void onTextChanged() { super.onTextChanged(); if (this.autoUpdateOnChange) { String text = this.validator.apply(getText()); - this.stringValue.setStringValue(this.numbers ? format.parse(text, new ParsePosition(0)).toString() : getText()); + this.stringValue + .setStringValue(this.numbers ? format.parse(text, new ParsePosition(0)).toString() : getText()); } } @@ -271,7 +280,8 @@ public TextFieldWidget value(IStringValue stringValue) { } /** - * Normally, Tooltips on text field widgets are used to display the contents of the widget when the scrollbar is active. + * Normally, Tooltips on text field widgets are used to display the contents of the widget when the scrollbar is + * active. * This value is an override, that allows the methods provided by {@link ITooltip} to be used.
* Every method that adds a tooltip from {@link ITooltip} is overridden to enable the {@link #tooltipOverride}. * diff --git a/src/test/java/brachy/modularui/CodecTest.java b/src/test/java/brachy/modularui/CodecTest.java index f13d26b9..35052f32 100644 --- a/src/test/java/brachy/modularui/CodecTest.java +++ b/src/test/java/brachy/modularui/CodecTest.java @@ -17,12 +17,11 @@ import brachy.modularui.widget.Widget; import brachy.modularui.widget.sizer.StandardResizer; -import com.mojang.serialization.Codec; -import com.mojang.serialization.JsonOps; - import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.serialization.Codec; +import com.mojang.serialization.JsonOps; import org.junit.jupiter.api.Test; import java.util.Objects; @@ -37,7 +36,7 @@ public class CodecTest { // TODO fix tests that attempt to load the mc server - //@Test + // @Test void resizer() { widgetTest(new Widget<>() .name("cool name") @@ -51,12 +50,13 @@ void resizer() { .decoration()); } - //@Test + // @Test void drawable() { drawableTest(IDrawable.EMPTY); drawableTest(IDrawable.NONE); decodeTest(new JsonPrimitive("null"), IDrawable.CODEC, IDrawable.EMPTY); - drawableTest(IDrawable.of(new Rectangle().color(Color.GREEN.main), GuiTextures.BOOKMARK, new Circle().color(Color.RED.main, Color.BLUE.main))); + drawableTest(IDrawable.of(new Rectangle().color(Color.GREEN.main), GuiTextures.BOOKMARK, + new Circle().color(Color.RED.main, Color.BLUE.main))); } @Test @@ -64,7 +64,8 @@ void text() { // NOTE: integer colors do not work properly when they have an alpha value due to a Minecraft bug. // I fixed this in TextColorMixin, but mixins are not applied in testing. test(ModularComponent.CODEC.mutableCodec(), Text.str("Hello"), false); - test(ModularComponent.CODEC.mutableCodec(), Text.str("World").style(Text.UNDERLINE).color(Color.withAlpha(Color.GREEN.main, 0)), false); + test(ModularComponent.CODEC.mutableCodec(), + Text.str("World").style(Text.UNDERLINE).color(Color.withAlpha(Color.GREEN.main, 0)), false); test(ModularComponent.CODEC.mutableCodec(), Text.comp( Text.str("Hello ").color(Color.withAlpha(Color.BLUE.main, 0)), Text.lang("World").scale(1.5f)).alignment(Alignment.BottomCenter), false); @@ -97,9 +98,10 @@ void color() { TestUtil.repeatRnd(10, CodecTest::testColorCMYK); } - //@Test + // @Test void widgetTheme() { - test(IThemeApi.FALLBACK.getCodec().codec(), WidgetTheme.darkTextNoShadow(1, 2, GuiTextures.MENU_BACKGROUND), false); + test(IThemeApi.FALLBACK.getCodec().codec(), WidgetTheme.darkTextNoShadow(1, 2, GuiTextures.MENU_BACKGROUND), + false); } private static void testColorHex(Random rnd) { diff --git a/src/test/java/brachy/modularui/ColorTest.java b/src/test/java/brachy/modularui/ColorTest.java index 036bf623..70803a83 100644 --- a/src/test/java/brachy/modularui/ColorTest.java +++ b/src/test/java/brachy/modularui/ColorTest.java @@ -7,8 +7,8 @@ import java.util.Arrays; -import static org.junit.jupiter.api.AssertionFailureBuilder.assertionFailure; import static brachy.modularui.utils.Color.*; +import static org.junit.jupiter.api.AssertionFailureBuilder.assertionFailure; public class ColorTest { @@ -86,7 +86,8 @@ static void assertColor(int c1, int c2, int tolerance, String extraMsg) { throw assertionFailure() .expected(Arrays.toString(Color.getARGBValues(c1))) .actual(Arrays.toString(Color.getARGBValues(c2))) - .reason("Color components differ by " + Color.getLargestDiff(c1, c2) + ", but only " + tolerance + " is allowed. ") + .reason("Color components differ by " + Color.getLargestDiff(c1, c2) + ", but only " + tolerance + + " is allowed. ") .message(extraMsg) .build(); }