Merge branch '1.21.4' into 1.21.1

# Conflicts:
#	changelog.md
#	gradle.properties
#	src/main/java/one/oth3r/sit/screen/ClickableImageWidget.java
#	src/main/java/one/oth3r/sit/screen/ConfigScreen.java
#	src/main/java/one/oth3r/sit/screen/TextureButtonWidget.java
This commit is contained in:
Oth3r 2025-05-18 13:57:24 -05:00
commit b7b3b39d82
65 changed files with 960 additions and 528 deletions

View file

@ -1,8 +1,18 @@
package one.oth3r.sit;
import net.fabricmc.api.ClientModInitializer;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.util.Identifier;
import one.oth3r.otterlib.client.screen.ConfigScreen;
import one.oth3r.otterlib.client.screen.utl.CustomImage;
import one.oth3r.otterlib.client.screen.utl.SimpleButton;
import one.oth3r.sit.file.FileData;
import one.oth3r.sit.utl.Data;
import one.oth3r.sit.utl.Events;
import one.oth3r.sit.utl.Utl;
import java.net.URI;
import java.util.List;
public class SitClient implements ClientModInitializer {
@ -12,5 +22,18 @@ public class SitClient implements ClientModInitializer {
Events.registerClient();
}
public static Screen getConfigScreen(Screen parent) {
return new ConfigScreen(parent, Utl.lang("sit!.screen.config"),
new CustomImage(Identifier.of(Data.MOD_ID, "textures/gui/banner.png"),128, 72),
List.of(
SimpleButton.Templates.fileEditor(Utl.lang("config.server"), FileData.getServerConfig(), new CustomImage(Identifier.of(Data.MOD_ID, "server_button"),246,26)).build(),
SimpleButton.Templates.fileEditor(Utl.lang("config.sitting"), FileData.getSittingConfig(), new CustomImage(Identifier.of(Data.MOD_ID, "sitting_button"), 246, 26)).build()
),
List.of(
SimpleButton.Templates.warning(Utl.lang("sit!.gui.button.issues")).openLink("https://github.com/Oth3r/Sit/issues").build(),
new SimpleButton.Builder(Utl.lang("sit!.gui.button.website")).openLink("https://modrinth.com/mod/sit!").build(),
SimpleButton.Templates.done(Utl.lang("gui.done")).build(),
SimpleButton.Templates.donate(Utl.lang("sit!.gui.button.donate")).openLink(URI.create("https://ko-fi.com/oth3r")).build()
));
}
}

View file

@ -14,6 +14,7 @@ import one.oth3r.sit.utl.Data;
import one.oth3r.sit.utl.Logic;
import one.oth3r.sit.utl.Utl;
import java.awt.*;
import java.util.concurrent.CompletableFuture;
public class SitCommand {
@ -49,7 +50,7 @@ public class SitCommand {
if (player == null) {
if (args[0].equalsIgnoreCase("reload")) {
Logic.reload();
Data.LOGGER.info(Utl.lang("sit!.chat.reloaded").getString());
Data.LOGGER.info(Utl.lang("sit!.chat.reloaded").toString());
}
return 1;
}
@ -75,7 +76,7 @@ public class SitCommand {
if (args[0].equalsIgnoreCase("reload")) {
Logic.reload();
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").formatted(Formatting.GREEN)));
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").color(Color.GREEN)).b());
}
if (args[0].equalsIgnoreCase("purgeChairEntities")) Utl.Entity.purge(player,true);

View file

@ -9,6 +9,7 @@ import net.minecraft.util.Identifier;
import one.oth3r.sit.utl.Utl;
import java.util.ArrayList;
import java.util.Objects;
public class CustomBlock {
@ -104,4 +105,16 @@ public class CustomBlock {
// not returning true in the loop because there might be a (!) not tag that the block might fall into, after the block was already in another tag
return tagCheck;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
CustomBlock that = (CustomBlock) o;
return Objects.equals(blockIds, that.blockIds) && Objects.equals(blockTags, that.blockTags) && Objects.equals(blockStates, that.blockStates);
}
@Override
public int hashCode() {
return Objects.hash(blockIds, blockTags, blockStates);
}
}

View file

@ -1,101 +0,0 @@
package one.oth3r.sit.file;
import net.fabricmc.loader.api.FabricLoader;
import one.oth3r.sit.utl.Data;
import one.oth3r.sit.utl.Utl;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public interface CustomFile <T extends CustomFile<T>> {
void reset();
/**
* saves the current instance to file
*/
default void save() {
if (!getFile().exists()) {
Data.LOGGER.info(String.format("Creating new `%s`", getFile().getName()));
}
try (BufferedWriter writer = Files.newBufferedWriter(getFile().toPath(), StandardCharsets.UTF_8)) {
writer.write(Utl.getGson().toJson(this));
} catch (Exception e) {
Data.LOGGER.error(String.format("ERROR SAVING '%s`: %s", getFile().getName(), e.getMessage()));
}
}
/**
* loads the file to the current instance using updateFromReader()
*/
default void load() {
File file = getFile();
if (!file.exists()) fileNotExist();
// try reading the file
try (BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
updateFromReader(reader);
} catch (Exception e) {
Data.LOGGER.error(String.format("ERROR LOADING '%s`: %s", file.getName(),e.getMessage()));
}
}
default void updateFromReader(BufferedReader reader) {
// try to read the json
T file;
try {
file = Utl.getGson().fromJson(reader, getFileClass());
} catch (Exception e) {
throw new NullPointerException();
}
// throw null if the fileData is null or version is null
if (file == null) throw new NullPointerException();
// update the instance
file.update();
// load the file to the current object
loadFileData(file);
}
@NotNull
Class<T> getFileClass();
/**
* loads the data from the file object into the current object
* @param newFile the file to take the properties from
*/
void loadFileData(T newFile);
/**
* updates the file based on the version number of the current instance
*/
void update();
/**
* logic for the file not existing when loading, defaults to saving
*/
default void fileNotExist() {
// try to make the config directory
try {
Files.createDirectories(Paths.get(getDirectory()));
} catch (Exception e) {
Data.LOGGER.error("Failed to create config directory. Canceling all config loading...");
return;
}
save();
}
String getFileName();
default String getDirectory() {
return FabricLoader.getInstance().getConfigDir().toFile()+"/";
}
default File getFile() {
return new File(getDirectory()+getFileName());
}
}

View file

@ -7,6 +7,7 @@ import net.minecraft.registry.tag.TagKey;
import net.minecraft.util.Identifier;
import java.util.ArrayList;
import java.util.Objects;
public class CustomItem {
@SerializedName("item-ids")
@ -21,6 +22,11 @@ public class CustomItem {
this.itemTags = itemTags;
}
public CustomItem(CustomItem customItem) {
this.itemIDs = new ArrayList<>(customItem.itemIDs);
this.itemTags = new ArrayList<>(customItem.itemTags);
}
public ArrayList<String> getItemIDs() {
return itemIDs;
}
@ -62,4 +68,16 @@ public class CustomItem {
// not returning true in the loop because there might be a (!) not tag that the item might fall into, after the item was already in another tag
return tagCheck;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
CustomItem that = (CustomItem) o;
return Objects.equals(itemIDs, that.itemIDs) && Objects.equals(itemTags, that.itemTags);
}
@Override
public int hashCode() {
return Objects.hash(itemIDs, itemTags);
}
}

View file

@ -3,6 +3,7 @@ package one.oth3r.sit.file;
import com.google.gson.annotations.SerializedName;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
public class HandSetting {
@ -21,6 +22,11 @@ public class HandSetting {
this.filter = filter;
}
public HandSetting(HandSetting handSetting) {
this.sittingRequirement = handSetting.sittingRequirement;
this.filter = new Filter(handSetting.filter);
}
public SittingRequirement getSittingRequirement() {
return sittingRequirement;
}
@ -52,6 +58,12 @@ public class HandSetting {
this.customItems = customItems;
}
public Filter(Filter filter) {
this.invert = filter.invert;
this.presets = new Presets(filter.presets);
this.customItems = new CustomItem(filter.customItems);
}
public Boolean isInverted() {
return invert;
}
@ -80,6 +92,12 @@ public class HandSetting {
this.usable = usable;
}
public Presets(Presets presets) {
this.block = presets.block;
this.food = presets.food;
this.usable = presets.usable;
}
public boolean isBlock() {
return block;
}
@ -91,6 +109,42 @@ public class HandSetting {
public boolean isUsable() {
return usable;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Presets presets = (Presets) o;
return block == presets.block && food == presets.food && usable == presets.usable;
}
@Override
public int hashCode() {
return Objects.hash(block, food, usable);
}
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Filter filter = (Filter) o;
return Objects.equals(invert, filter.invert) && Objects.equals(presets, filter.presets) && Objects.equals(customItems, filter.customItems);
}
@Override
public int hashCode() {
return Objects.hash(invert, presets, customItems);
}
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
HandSetting that = (HandSetting) o;
return sittingRequirement == that.sittingRequirement && Objects.equals(sittingRequirementOptions, that.sittingRequirementOptions) && Objects.equals(filter, that.filter);
}
@Override
public int hashCode() {
return Objects.hash(sittingRequirement, sittingRequirementOptions, filter);
}
}

View file

@ -4,6 +4,7 @@ import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import one.oth3r.otterlib.chat.CTxT;
import one.oth3r.sit.Sit;
import one.oth3r.sit.utl.Data;
@ -20,14 +21,19 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LangReader {
private static final Map<String, String> defaultLangMap = new HashMap<>();
private static final Map<String, String> languageMap = new HashMap<>();
private final String translationKey;
private final Object[] placeholders;
public LangReader(String translationKey, Object... placeholders) {
this.translationKey = translationKey;
this.placeholders = placeholders;
}
public MutableText getTxT() {
public CTxT getTxT() {
String translated = getLanguageValue(translationKey);
if (placeholders != null && placeholders.length > 0) {
//removed all double \\ and replaces with \
@ -35,7 +41,8 @@ public class LangReader {
String regex = "%\\d*\\$?[dfs]";
Matcher anyMatch = Pattern.compile(regex).matcher(translated);
Matcher endMatch = Pattern.compile(regex+"$").matcher(translated);
//Arraylist with all the %(#$)[dfs]
// Arraylist with all the %(#$)[dfs]
ArrayList<String> matches = new ArrayList<>();
while (anyMatch.find()) {
String match = anyMatch.group();
@ -51,7 +58,7 @@ public class LangReader {
}
//if there are placeholders specified, and the split is more than 1, it will replace %(dfs) with the placeholder objects
if (parts.length > 1) {
MutableText txt = Text.empty();
CTxT txt = new CTxT("");
int i = 0;
for (String match : matches) {
int get = i;
@ -62,47 +69,56 @@ public class LangReader {
}
if (parts.length != i) txt.append(parts[i]);
//convert the obj into txt
Object obj = placeholders[get];
if (obj instanceof Text) txt.append((Text) obj);
else txt.append(String.valueOf(obj));
txt.append(getTxTFromObj(placeholders[get]));
i++;
}
if (parts.length != i) txt.append(parts[i]);
return txt;
return new CTxT(txt);
}
}
return Text.empty().append(translated);
return new CTxT(translated);
}
private CTxT getTxTFromObj(Object obj) {
if (obj instanceof CTxT) return (((CTxT) obj));
else if (obj instanceof Text) return new CTxT((MutableText) obj);
else return new CTxT(String.valueOf(obj));
}
public static LangReader of(String translationKey, Object... placeholders) {
return new LangReader(translationKey, placeholders);
}
public static void loadLanguageFile() {
ClassLoader classLoader = Sit.class.getClassLoader();
Type tToken = new TypeToken<Map<String, String>>(){}.getType();
try {
InputStream inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/" + FileData.getServerConfig().getLang() +".json");
// if the input stream is null, the language file wasn't found
if (inputStream == null) {
// try loading the default language file
inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/" + new ServerConfig().getLang() +".json");
Data.LOGGER.error("COULDN'T LOAD THE LANGUAGE FILE. RESETTING TO en_us.");
}
// if the input stream is still null, throw an exception
if (inputStream == null) throw new IllegalArgumentException("UNABLE TO LOAD THE ENGLISH LANGUAGE FILE.");
Type type = new TypeToken<Map<String, String>>(){}.getType();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
languageMap.putAll(new Gson().fromJson(reader, type));
// close the input stream
inputStream.close();
// load the config language
Reader selectionReader = new InputStreamReader(getInputStream(false), StandardCharsets.UTF_8);
languageMap.putAll(new Gson().fromJson(selectionReader, tToken));
// load the default language as well (fallback)
Reader defaultReader = new InputStreamReader(getInputStream(true), StandardCharsets.UTF_8);
defaultLangMap.putAll(new Gson().fromJson(defaultReader, tToken));
} catch (Exception e) {
Data.LOGGER.error(e.getMessage());
Data.LOGGER.info("ERROR WITH LANGUAGE FILE - PLEASE REPORT WITH THE ERROR LOG");
Data.LOGGER.info(e.getMessage());
}
}
private static InputStream getInputStream(boolean english) {
ClassLoader classLoader = Sit.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/"+FileData.getServerConfig().getLang()+".json");
// make null if english
if (english) inputStream = null;
// if it cant read (null), try again, but with the english file
if (inputStream == null) inputStream = classLoader.getResourceAsStream("assets/sit-oth3r/lang/"+new ServerConfig().getLang()+".json");
// if null after that, throw an exception
if (inputStream == null) throw new IllegalArgumentException("CANT LOAD THE LANGUAGE FILE. SIT! WILL BREAK.");
return inputStream;
}
public static String getLanguageValue(String key) {
return languageMap.getOrDefault(key, key);
return languageMap.getOrDefault(key, defaultLangMap.getOrDefault(key, key));
}
}

View file

@ -1,10 +1,13 @@
package one.oth3r.sit.file;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import net.minecraft.util.Hand;
import one.oth3r.otterlib.file.CustomFile;
import one.oth3r.otterlib.file.FileSettings;
import one.oth3r.sit.utl.Data;
import one.oth3r.sit.utl.Utl;
import org.jetbrains.annotations.NotNull;
@ -13,8 +16,11 @@ import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;
@ -24,9 +30,9 @@ public class ServerConfig implements CustomFile<ServerConfig> {
private Double version = 2.2;
@SerializedName("lang")
private String lang = "en_us";
private String lang = "en_US";
@SerializedName("lang-options")
private final String langOptions = "en_us, it_it, pt_br, tr_tr, zh_tw, zh_ch, de_de";
private final String langOptions = "en_US, it_IT, pt_BR, tr_TR, zh_TW, zh_CH, de_DE";
@SerializedName("keep-active")
private Boolean keepActive = true;
@ -51,7 +57,7 @@ public class ServerConfig implements CustomFile<ServerConfig> {
public ServerConfig() {}
public ServerConfig(ServerConfig serverConfig) {
loadFileData(serverConfig);
copyFileData(serverConfig);
}
public ServerConfig(Double version, String lang, boolean keepActive, boolean sitWhileSeated,
@ -151,6 +157,18 @@ public class ServerConfig implements CustomFile<ServerConfig> {
public boolean isFullBlocks() {
return fullBlocks;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
PresetBlocks that = (PresetBlocks) o;
return stairs == that.stairs && slabs == that.slabs && carpets == that.carpets && fullBlocks == that.fullBlocks;
}
@Override
public int hashCode() {
return Objects.hash(stairs, slabs, carpets, fullBlocks);
}
}
public static class YDifferenceLimit {
@ -187,11 +205,36 @@ public class ServerConfig implements CustomFile<ServerConfig> {
public void setBelow(Double below) {
this.below = below;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
YDifferenceLimit that = (YDifferenceLimit) o;
return Objects.equals(above, that.above) && Objects.equals(below, that.below);
}
@Override
public int hashCode() {
return Objects.hash(above, below);
}
}
@Override
public FileSettings getFileSettings() {
return new FileSettings(Data.LOGGER);
}
/**
* the path to the file - including the extension ex. usr/config/custom-file.json
*/
@Override
public Path getFilePath() {
return Paths.get(Data.CONFIG_DIR, "server-config.json");
}
@Override
public void reset() {
loadFileData(new ServerConfig());
copyFileData(new ServerConfig());
}
@Override
@ -199,8 +242,13 @@ public class ServerConfig implements CustomFile<ServerConfig> {
return ServerConfig.class;
}
/**
* loads the data from the file object into the current object - DEEP COPY
*
* @param newFile the file to take the properties from
*/
@Override
public void loadFileData(ServerConfig newFile) {
public void copyFileData(ServerConfig newFile) {
this.version = newFile.version;
this.lang = newFile.lang;
this.keepActive = newFile.keepActive;
@ -216,8 +264,13 @@ public class ServerConfig implements CustomFile<ServerConfig> {
this.interactionBlocks = newFile.interactionBlocks.stream().map(CustomBlock::new).collect(Collectors.toCollection(ArrayList::new));
}
/**
* updates the file based on the version number of the current instance
*
* @param json
*/
@Override
public void update() {
public void update(JsonElement json) {
/// update to 2.1, just a new list, nothing to change
/// update to 2.2, new settings, no changes
if (version >= 2.0 && version <= 2.1) {
@ -226,18 +279,8 @@ public class ServerConfig implements CustomFile<ServerConfig> {
}
@Override
public String getFileName() {
return "server-config.json";
}
@Override
public String getDirectory() {
return Data.CONFIG_DIR;
}
@Override
public void fileNotExist() {
CustomFile.super.fileNotExist();
public void createDirectory() {
CustomFile.super.createDirectory();
// try checking the old/legacy config directory for the file
if (Legacy.getLegacyFile().exists()) {
Data.LOGGER.info("Updating Sit!.properties to sit!/config.json");
@ -245,6 +288,25 @@ public class ServerConfig implements CustomFile<ServerConfig> {
}
}
@Override
public ServerConfig clone() {
ServerConfig clone = new ServerConfig();
clone.copyFileData(this);
return clone;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
ServerConfig that = (ServerConfig) o;
return Objects.equals(version, that.version) && Objects.equals(lang, that.lang) && Objects.equals(keepActive, that.keepActive) && Objects.equals(sitWhileSeated, that.sitWhileSeated) && Objects.equals(presetBlocks, that.presetBlocks) && Objects.equals(yDifferenceLimit, that.yDifferenceLimit) && Objects.equals(customEnabled, that.customEnabled) && Objects.equals(sittingBlocks, that.sittingBlocks) && Objects.equals(blacklistedBlocks, that.blacklistedBlocks) && Objects.equals(interactionBlocks, that.interactionBlocks);
}
@Override
public int hashCode() {
return Objects.hash(version, lang, langOptions, keepActive, sitWhileSeated, presetBlocks, yDifferenceLimit, customEnabled, sittingBlocks, blacklistedBlocks, interactionBlocks);
}
protected static class Legacy {
/**
* gets the legacy file, from the old directory for fabric, and the same one for spigot

View file

@ -3,6 +3,7 @@ package one.oth3r.sit.file;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.Objects;
public class SittingBlock extends CustomBlock {
@SerializedName("sitting-height")
@ -27,4 +28,17 @@ public class SittingBlock extends CustomBlock {
super(sittingBlock);
this.sittingHeight = sittingBlock.sittingHeight;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
SittingBlock that = (SittingBlock) o;
return Objects.equals(sittingHeight, that.sittingHeight);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), sittingHeight);
}
}

View file

@ -1,10 +1,17 @@
package one.oth3r.sit.file;
import com.google.common.base.Objects;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import net.minecraft.util.Hand;
import one.oth3r.otterlib.file.CustomFile;
import one.oth3r.otterlib.file.FileSettings;
import one.oth3r.sit.utl.Data;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SittingConfig implements CustomFile<SittingConfig> {
@SerializedName("version")
@ -29,7 +36,7 @@ public class SittingConfig implements CustomFile<SittingConfig> {
}
public SittingConfig(SittingConfig sittingConfig) {
loadFileData(sittingConfig);
copyFileData(sittingConfig);
}
public Double getVersion() {
@ -64,9 +71,19 @@ public class SittingConfig implements CustomFile<SittingConfig> {
return offHand;
}
@Override
public FileSettings getFileSettings() {
return new FileSettings(Data.LOGGER);
}
@Override
public Path getFilePath() {
return Paths.get(Data.CONFIG_DIR, "sitting-config.json");
}
@Override
public void reset() {
loadFileData(new SittingConfig());
copyFileData(new SittingConfig());
}
@Override
@ -75,24 +92,35 @@ public class SittingConfig implements CustomFile<SittingConfig> {
}
@Override
public void loadFileData(SittingConfig newFile) {
this.version = newFile.version;
this.enabled = newFile.enabled;
this.handSitting = newFile.handSitting;
this.mainHand = newFile.mainHand;
this.offHand = newFile.offHand;
public void copyFileData(SittingConfig sittingConfig) {
this.version = sittingConfig.version;
this.enabled = sittingConfig.enabled;
this.handSitting = sittingConfig.handSitting;
this.mainHand = new HandSetting(sittingConfig.mainHand);
this.offHand = new HandSetting(sittingConfig.offHand);
}
@Override
public void update() {}
public void update(JsonElement jsonElement) {
@Override
public String getFileName() {
return "sitting-config.json";
}
@Override
public String getDirectory() {
return Data.CONFIG_DIR;
public SittingConfig clone() {
SittingConfig clone = new SittingConfig();
clone.copyFileData(this);
return clone;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
SittingConfig that = (SittingConfig) o;
return Objects.equal(version, that.version) && Objects.equal(enabled, that.enabled) && Objects.equal(handSitting, that.handSitting) && Objects.equal(mainHand, that.mainHand) && Objects.equal(offHand, that.offHand);
}
@Override
public int hashCode() {
return Objects.hashCode(version, enabled, handSitting, mainHand, offHand);
}
}

View file

@ -6,19 +6,21 @@ import net.minecraft.server.command.ReloadCommand;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Formatting;
import one.oth3r.sit.file.FileData;
import one.oth3r.sit.utl.Data;
import one.oth3r.sit.utl.Logic;
import one.oth3r.sit.utl.Utl;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.awt.*;
@Mixin(ReloadCommand.class)
public class ReloadCommandMixin {
@Inject(at = @At("TAIL"), method = "register")
private static void register(CommandDispatcher<ServerCommandSource> dispatcher, CallbackInfo ci) {
FileData.loadFiles();
Logic.reload();
// make sure the server isn't null
MinecraftServer server = Data.getServer();
@ -27,7 +29,7 @@ public class ReloadCommandMixin {
// send a reloaded message to all players with permissions
for (ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) {
if (player.isCreativeLevelTwoOp()) {
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").formatted(Formatting.GREEN)));
player.sendMessage(Utl.messageTag().append(Utl.lang("sit!.chat.reloaded").color(Color.GREEN)).b());
}
}
}

View file

@ -1,31 +0,0 @@
package one.oth3r.sit.screen;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import java.util.function.Supplier;
public class ClickableImageWidget extends ButtonWidget {
private final Identifier image;
public ClickableImageWidget(int x, int y, int width, int height, Tooltip tooltip, Identifier image, ButtonWidget.PressAction onPress) {
super(x, y, width, height, Text.empty(), onPress, Supplier::get);
this.image = image;
this.setTooltip(tooltip);
}
@Override
protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {
context.setShaderColor(1.0f, 1.0f, 1.0f, this.alpha);
RenderSystem.enableBlend();
RenderSystem.enableDepthTest();
context.drawTexture(image,
this.getX(), this.getY(), 0.0f, 0.0f, this.getWidth(), this.getHeight(), this.getWidth(), this.getHeight());
context.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
}
}

View file

@ -1,79 +0,0 @@
package one.oth3r.sit.screen;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.ConfirmLinkScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import one.oth3r.sit.file.FileData;
import one.oth3r.sit.utl.Data;
import java.net.URI;
public class ConfigScreen extends Screen {
protected final Screen parent;
public ConfigScreen(Screen parent) {
super(Text.translatable("sit!.screen.config"));
this.parent = parent;
}
@Override
protected void init() {
int startY = this.height / 4 + 48;
int spacing = 36;
TextureButtonWidget serverConfigButton = this.addDrawableChild(new TextureButtonWidget.Builder(Text.translatable("config.server"),
(button) -> client.setScreen(new UnderConstructionScreen(this, FileData.getServerConfig())), false)
.dimensions(250,30).texture(Identifier.of(Data.MOD_ID, "server_button"), 246, 26).build());
serverConfigButton.setPosition(this.width / 2 - (serverConfigButton.getWidth()/2), startY);
TextureButtonWidget sittingConfigButton = this.addDrawableChild(new TextureButtonWidget.Builder(Text.translatable("config.sitting"),
(button) -> client.setScreen(new UnderConstructionScreen(this, FileData.getSittingConfig())), false)
.dimensions(250,30).texture(Identifier.of(Data.MOD_ID, "sitting_button"), 246, 26).build());
sittingConfigButton.setPosition(this.width / 2 - (sittingConfigButton.getWidth()/2), startY+36);
TextureButtonWidget issuesButton = this.addDrawableChild(new TextureButtonWidget.Builder(Text.translatable("sit!.gui.button.issues"),
ConfirmLinkScreen.opening(this, URI.create("https://github.com/Oth3r/Sit/issues")), true)
.dimensions(20,20).texture(Identifier.of(Data.MOD_ID, "issues"), 15, 15).build());
issuesButton.setPosition(this.width / 2 - 125, startY + 72 + 12);
this.addDrawableChild(ButtonWidget.builder(Text.translatable("sit!.gui.button.website"),
ConfirmLinkScreen.opening(this, URI.create("https://modrinth.com/mod/sit!"))
).dimensions(this.width / 2 - 100, startY + 72 + 12, 98, 20).build());
this.addDrawableChild(ButtonWidget.builder(Text.translatable("gui.done"), (button) -> {
close();
}).dimensions(this.width / 2 + 2, startY + 72 + 12, 98, 20).build());
TextureButtonWidget donateButton = this.addDrawableChild(new TextureButtonWidget.Builder(Text.translatable("sit!.gui.button.donate"),
ConfirmLinkScreen.opening(this, URI.create("https://Ko-fi.com/oth3r")), true)
.dimensions(20,20).texture(Identifier.of(Data.MOD_ID, "donate"), 15, 15).build());
donateButton.setPosition(this.width / 2 + 105, startY + 72 + 12);
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta);
// todo fade in like the title screen on first load?
renderBanner(context,width/2 - 64,this.height / 4 -38,1);
}
@Override
public void close() {
this.client.setScreen(parent);
}
private void renderBanner(DrawContext context, int x, int y, float alpha) {
RenderSystem.enableBlend();
context.drawTexture(Identifier.of(Data.MOD_ID, "textures/gui/banner.png"),
x, y, 0.0f, 0.0f, 128, 72, 128, 72);
RenderSystem.disableBlend();
}
}

View file

@ -2,10 +2,11 @@ package one.oth3r.sit.screen;
import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import com.terraformersmc.modmenu.api.ModMenuApi;
import one.oth3r.sit.SitClient;
public class ModMenu implements ModMenuApi {
@Override
public ConfigScreenFactory<?> getModConfigScreenFactory() {
return ConfigScreen::new;
return SitClient::getConfigScreen;
}
}

View file

@ -1,85 +0,0 @@
package one.oth3r.sit.screen;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
public class TextureButtonWidget extends ButtonWidget {
//todo gray support
protected final Identifier texture;
protected final int textureWidth;
protected final int textureHeight;
protected final boolean tooltip;
TextureButtonWidget(int width, int height, Text message, int textureWidth, int textureHeight, Identifier texture, ButtonWidget.PressAction onPress, @Nullable ButtonWidget.NarrationSupplier narrationSupplier, boolean tooltip) {
super(0, 0, width, height, message, onPress, narrationSupplier == null ? DEFAULT_NARRATION_SUPPLIER : narrationSupplier);
this.textureWidth = textureWidth;
this.textureHeight = textureHeight;
this.texture = texture;
this.tooltip = tooltip;
if (tooltip) setTooltip(Tooltip.of(message));
}
@Override
public void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {
super.renderWidget(context, mouseX, mouseY, delta);
int x = this.getX() + this.getWidth() / 2 - this.textureWidth / 2;
int y = this.getY() + this.getHeight() / 2 - this.textureHeight / 2;
context.drawGuiTexture(this.texture, x, y, this.textureWidth, this.textureHeight);
}
@Override
public void drawMessage(DrawContext context, TextRenderer textRenderer, int color) {
if (!this.tooltip) super.drawMessage(context, textRenderer, color);
}
public static class Builder {
private final Text text;
private final ButtonWidget.PressAction onPress;
private final boolean hideText;
private int width = 150;
private int height = 20;
@Nullable
private Identifier texture;
private int textureWidth;
private int textureHeight;
@Nullable
ButtonWidget.NarrationSupplier narrationSupplier;
public Builder(Text text, ButtonWidget.PressAction onPress, boolean hideText) {
this.text = text;
this.onPress = onPress;
this.hideText = hideText;
}
public Builder dimensions(int width, int height) {
this.width = width;
this.height = height;
return this;
}
public Builder texture(Identifier texture, int width, int height) {
this.texture = texture;
this.textureWidth = width;
this.textureHeight = height;
return this;
}
public Builder narration(ButtonWidget.NarrationSupplier narrationSupplier) {
this.narrationSupplier = narrationSupplier;
return this;
}
public TextureButtonWidget build() {
if (this.texture == null) {
throw new IllegalStateException("Sprite not set");
}
return new TextureButtonWidget(width,height,text,textureWidth,textureHeight,texture,onPress,narrationSupplier,hideText);
}
}
}

View file

@ -1,79 +0,0 @@
package one.oth3r.sit.screen;
import net.minecraft.client.gui.screen.ConfirmLinkScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.Util;
import one.oth3r.sit.file.CustomFile;
import one.oth3r.sit.file.SittingConfig;
import one.oth3r.sit.utl.Data;
import one.oth3r.sit.utl.Utl;
import java.net.URI;
import java.nio.file.Paths;
public class UnderConstructionScreen<T extends CustomFile<T>> extends Screen {
protected final Screen parent;
protected T file;
public UnderConstructionScreen(Screen parent, T file) {
super(Text.translatable("sit!.screen.config"));
this.parent = parent;
this.file = file;
}
@Override
protected void init() {
int startY = this.height / 5-4;
ButtonWidget foxPNG = this.addDrawableChild(new ClickableImageWidget(70,70,140,140, Tooltip.of(Text.of("Art by @bunnestbun")),
Identifier.of(Data.MOD_ID, "textures/gui/fox.png"), ConfirmLinkScreen.opening(this, URI.create("https://www.instagram.com/bunnestbun/"))));
foxPNG.setPosition(this.width / 2 - (foxPNG.getWidth()/2), startY-35);
ButtonWidget openFileButton = this.addDrawableChild(new ButtonWidget.Builder(Text.translatable("sit!.gui.button.file"),
(button) -> Util.getOperatingSystem().open(this.file.getFile()))
.dimensions(0, 0, 118 ,20).build());
openFileButton.setPosition(this.width / 2 - 70, startY+110);
TextureButtonWidget folderButton = this.addDrawableChild(new TextureButtonWidget.Builder(Text.translatable("sit!.gui.button.folder"),
(button) -> Util.getOperatingSystem().open(Paths.get(this.file.getFile().getParent())), true)
.dimensions(20,20).texture(Identifier.of(Data.MOD_ID, "folder"), 15, 15).build());
folderButton.setPosition(this.width / 2 + 50, startY + 110);
TextureButtonWidget resetButton = this.addDrawableChild(new TextureButtonWidget.Builder(Text.translatable("sit!.gui.button.reset"),
(button) -> {
this.file.reset();
this.file.save();
}, true)
.dimensions(20,20).texture(Identifier.of(Data.MOD_ID, "reset_file"), 15, 15).build());
resetButton.setPosition(this.width / 2 -70, startY + 135);
ButtonWidget revertButton = this.addDrawableChild(new ButtonWidget.Builder(Text.translatable("sit!.gui.button.revert"),
(button) -> this.file.save())
.dimensions(0, 0, 118,20).build());
revertButton.setPosition(this.width / 2 - 48, startY+135);
ButtonWidget saveExitButton = this.addDrawableChild(new ButtonWidget.Builder(Text.translatable("sit!.gui.button.save"),
(button) -> {
this.file.load();
this.file.save();
// send the settings to the server if editing the sitting file and on a supported server
if (this.file instanceof SittingConfig && Data.isSupportedServer()) {
Utl.sendSettingsPackets();
}
this.client.setScreen(parent);
})
.dimensions(0, 0, 140,20).build());
saveExitButton.setPosition(this.width / 2 - 70, startY+168);
}
@Override
public void close() {
this.client.setScreen(parent);
}
}

View file

@ -1,5 +1,8 @@
package one.oth3r.sit.utl;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
@ -14,17 +17,19 @@ import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Formatting;
import one.oth3r.sit.SitClient;
import one.oth3r.sit.command.SitCommand;
import one.oth3r.sit.file.FileData;
import one.oth3r.sit.file.LangReader;
import one.oth3r.sit.file.SittingConfig;
import one.oth3r.sit.packet.SitPayloads;
import one.oth3r.sit.screen.ConfigScreen;
import org.lwjgl.glfw.GLFW;
import java.awt.*;
public class Events {
private static class Keybindings {
@ -54,7 +59,7 @@ public class Events {
ClientPlayerEntity player = client.player;
while (config__key.wasPressed()) {
client.setScreen(new ConfigScreen(client.currentScreen));
client.setScreen(SitClient.getConfigScreen(client.currentScreen));
}
/// anything below uses the player object, make sure it's not null
@ -74,7 +79,7 @@ public class Events {
} else {
// unsupported server message if not in a Sit! server
player.sendMessage(Utl.lang("sit!.chat.unsupported")
.formatted(Formatting.RED), true);
.color(Color.RED).b(), true);
}
}
}
@ -99,7 +104,7 @@ public class Events {
ServerPlayNetworking.send(context.player(),new SitPayloads.ResponsePayload(SitPayloads.ResponsePayload.VERSION));
// log the receiving of the packet from the player
Data.LOGGER.info(Utl.lang("sit!.console.player_settings",context.player().getName().getString()).getString());
Data.LOGGER.info(Utl.lang("sit!.console.player_settings",context.player().getName().getString()).toString());
})));
}
@ -109,7 +114,7 @@ public class Events {
// only update when needed
if (!Data.isSupportedServer()) {
Data.setSupportedServer(true);
Data.LOGGER.info(Utl.lang("sit!.console.connected",payload.value()).getString());
Data.LOGGER.info(Utl.lang("sit!.console.connected",payload.value()).toString());
}
}));
}
@ -179,7 +184,19 @@ public class Events {
if (player == null || player.isSpectator()) return ActionResult.PASS;
// consume if sitting, if not pass
return Logic.sit(player,hitResult.getBlockPos(),hitResult) ? ActionResult.CONSUME : ActionResult.PASS;
ActionResult result = Logic.canSit(player,hitResult.getBlockPos(),hitResult) ? ActionResult.CONSUME : ActionResult.PASS;
// todo test
if (result.equals(ActionResult.CONSUME)) {
try {
CommandDispatcher<ServerCommandSource> dispatcher = Data.getServer().getCommandSource().getDispatcher();
ParseResults<ServerCommandSource> parse = dispatcher.parse("sit", player.getCommandSource());
dispatcher.execute(parse);
} catch (CommandSyntaxException e) {
Data.LOGGER.error("Error executing sit command for player {}", player.getName().getString());
}
}
return result;
});
});

View file

@ -1,6 +1,5 @@
package one.oth3r.sit.utl;
import net.minecraft.block.*;
import net.minecraft.entity.decoration.DisplayEntity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
@ -9,14 +8,21 @@ import net.minecraft.util.Formatting;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import one.oth3r.sit.file.FileData;
import one.oth3r.sit.file.ServerConfig;
import one.oth3r.sit.file.SittingConfig;
import one.oth3r.sit.file.HandSetting;
import one.oth3r.sit.file.*;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
public class Logic {
public static boolean sit(ServerPlayerEntity player, BlockPos blockPos, @Nullable BlockHitResult hitResult) {
/**
* checks if the player can sit at the block specified
* @param player the player that's going to sit
* @param blockPos the position that the player is going to sit at
* @param hitResult nullable, not null if the player is sitting with their hand
* @return true if the player can sit with the conditions provided
*/
public static boolean canSit(ServerPlayerEntity player, BlockPos blockPos, @Nullable BlockHitResult hitResult) {
// cant sit if crouching
if (player.isSneaking()) return false;
@ -32,22 +38,44 @@ public class Logic {
if (!checkYLimits(player, blockPos)) return false;
ServerWorld serverWorld = player.getServerWorld();
BlockState blockState = serverWorld.getBlockState(blockPos);
Double sitHeight = Utl.getSittingHeight(blockState,player,blockPos,hitResult);
Double sitHeight = Utl.getSittingHeight(player,blockPos,hitResult);
// if the sit height is null, its not a sittable block
// if the sit height is null, it's not a sittable block
if (sitHeight == null) return false;
DisplayEntity.TextDisplayEntity entity = Utl.Entity.create(serverWorld,blockPos,sitHeight);
if (!checkPlayerSitAbility(entity)) return false;
// checks if the player can sit
return checkPlayerSitAbility(entity);
}
Utl.Entity.spawnSit(player, entity);
/**
* makes the player attempt to sit at the position provided (checks if the player can sit before)
* @param player the player that is sitting
* @param blockPos the pos the player is going to sit at
* @param hitResult nullable, not null if the player is sitting with their hand
* @return true if sitting was successful
*/
public static boolean sit(ServerPlayerEntity player, BlockPos blockPos, @Nullable BlockHitResult hitResult) {
if (!canSit(player, blockPos, hitResult)) return false;
// assets
ServerWorld serverWorld = player.getServerWorld();
Double sitHeight = Utl.getSittingHeight(player,blockPos,hitResult);
// shouldn't be null because we already checked, but do another check to clear IDE errors
assert sitHeight != null;
// spawn the entity and make the player sit
Utl.Entity.spawnSit(player, Utl.Entity.create(serverWorld,blockPos,sitHeight));
return true;
}
/**
* makes the player attempt to sit at the block they are looking at (range of 5)
* @param player the player who is trying to sit
* @return true if sitting was successful
*/
public static boolean sitLooking(ServerPlayerEntity player) {
return sit(player, Utl.getBlockPosPlayerIsLookingAt(player.getServerWorld(),player,5),null);
}
@ -172,6 +200,7 @@ public class Logic {
public static void reload() {
FileData.loadFiles();
FileData.saveFiles();
LangReader.loadLanguageFile();
}
/**
@ -199,11 +228,11 @@ public class Logic {
// send the player the actionbar message
return Utl.lang("sit!.chat.toggle_sit",
Utl.lang(messageKey).formatted(messageColor));
Utl.lang(messageKey).color(config.getEnabled()? Color.GREEN : Color.RED)).b();
} else {
// unsupported server message if not in a Sit! server
return Utl.lang("sit!.chat.unsupported")
.formatted(Formatting.RED);
.color(Color.RED).b();
}
}

View file

@ -17,9 +17,7 @@ import net.minecraft.item.ItemStack;
import net.minecraft.registry.Registries;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.text.TextColor;
import net.minecraft.util.*;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.HitResult;
@ -27,11 +25,13 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.RaycastContext;
import net.minecraft.world.World;
import one.oth3r.otterlib.chat.CTxT;
import one.oth3r.sit.file.*;
import one.oth3r.sit.packet.SitPayloads;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@ -152,14 +152,15 @@ public class Utl {
/**
* gets the sitting height for the provided blockstate, via memory loaded config from Data
* @param blockState the state of the block
* @param player the player to
* @param blockPos the pos of the block
* @param hit nullable, for the player interaction check
* @return null if not a valid block
*/
public static Double getSittingHeight(BlockState blockState, ServerPlayerEntity player, BlockPos blockPos, @Nullable BlockHitResult hit) {
public static Double getSittingHeight(ServerPlayerEntity player, BlockPos blockPos, @Nullable BlockHitResult hit) {
ServerWorld serverWorld = player.getServerWorld();
ServerConfig config = FileData.getServerConfig();
BlockState blockState = serverWorld.getBlockState(blockPos);
Block block = blockState.getBlock();
// make sure that the block that is being sit on has no interaction when hand sitting
@ -217,7 +218,7 @@ public class Utl {
// get the blockstate
BlockState blockState = player.getWorld().getBlockState(blockPos);
// check if the block is still there & the block is a valid sit block (by checking if there is a sit height for the block)
return !blockState.isAir() && getSittingHeight(blockState,player,blockPos,null) != null;
return !blockState.isAir() && getSittingHeight(player,blockPos,null) != null;
}
/**
@ -318,26 +319,32 @@ public class Utl {
// send a message if needed
if (message) {
player.sendMessage(messageTag().append(Utl.lang("sit!.chat.purged",Utl.lang("sit!.chat.purged.total",count).styled(
style -> style.withColor(Colors.LIGHT_GRAY).withItalic(true)
)).styled(
style -> style.withColor(Colors.GREEN)
)));
player.sendMessage(messageTag()
.append(lang("sit!.chat.purged",lang("sit!.chat.purged.total",count).color(Color.gray).b()).color(Color.GREEN)).b());
}
}
}
public static MutableText messageTag() {
return Text.literal("[").append(Text.literal("Sit!").styled(
style -> style.withColor(TextColor.parse("#c400ff").result().orElse(TextColor.fromFormatting(Formatting.DARK_PURPLE))))
).append("] ");
public static CTxT messageTag() {
return new CTxT("Sit!").btn(true).color(Color.decode("#c400ff")).append(" ");
}
/**
* gets a MutableText using the language key, if on server, using the custom lang reader
*/
public static MutableText lang(String key, Object... args) {
if (Data.isClient()) return Text.translatable(key, args);
public static CTxT lang(String key, Object... args) {
if (Data.isClient()) {
// we have to first convert all the CTxT's to the built version because minecraft lang reader doesn't know how to process it
// make a array with the same size of the args
Object[] fixedArgs = new Object[args.length];
// for every arg, build & add if CTxT or just add if not
for (var i = 0; i < args.length; i++) {
if (args[i] instanceof CTxT) fixedArgs[i] = ((CTxT) args[i]).b();
else fixedArgs[i] = args[i];
}
// return the translated text
return new CTxT(Text.translatable(key,fixedArgs));
}
else return LangReader.of(key, args).getTxT();
}