diff --git a/common/src/main/java/org/vivecraft/client/gui/framework/GuiVROptionSlider.java b/common/src/main/java/org/vivecraft/client/gui/framework/GuiVROptionSlider.java index ccbfa9de1..ea5ae2278 100644 --- a/common/src/main/java/org/vivecraft/client/gui/framework/GuiVROptionSlider.java +++ b/common/src/main/java/org/vivecraft/client/gui/framework/GuiVROptionSlider.java @@ -45,8 +45,7 @@ protected void applyValue() { double fullValue = this.enumOptions.denormalizeValue((float) this.value); dataholder.vrSettings.setOptionFloatValue(this.enumOptions, (float) fullValue); // with that keyboard changes don't work, if there are fewer options than pixels - InputType inputType = Minecraft.getInstance().getLastInputType(); - if (inputType == InputType.MOUSE) { + if (Minecraft.getInstance().getLastInputType() == InputType.MOUSE) { this.value = this.enumOptions.normalizeValue((float) fullValue); } } diff --git a/common/src/main/java/org/vivecraft/client_vr/settings/VRSettings.java b/common/src/main/java/org/vivecraft/client_vr/settings/VRSettings.java index 3aedddee5..fb5b8bf1f 100644 --- a/common/src/main/java/org/vivecraft/client_vr/settings/VRSettings.java +++ b/common/src/main/java/org/vivecraft/client_vr/settings/VRSettings.java @@ -4,7 +4,7 @@ */ package org.vivecraft.client_vr.settings; -import com.google.gson.JsonObject; +import com.google.gson.*; import com.mojang.blaze3d.pipeline.RenderTarget; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.language.I18n; @@ -16,25 +16,24 @@ import org.lwjgl.glfw.GLFW; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.vivecraft.client.Xplat; import org.vivecraft.client.utils.LangHelper; import org.vivecraft.client_vr.ClientDataHolderVR; import org.vivecraft.client_vr.VRState; import org.vivecraft.client_vr.gameplay.VRPlayer; import org.vivecraft.client_vr.gameplay.screenhandlers.KeyboardHandler; import org.vivecraft.client_vr.gui.PhysicalKeyboard; -import org.vivecraft.client_vr.settings.profile.ProfileManager; -import org.vivecraft.client_vr.settings.profile.ProfileReader; -import org.vivecraft.client_vr.settings.profile.ProfileWriter; import org.vivecraft.common.utils.math.Angle; import org.vivecraft.common.utils.math.Quaternion; import org.vivecraft.common.utils.math.Vector3; import org.vivecraft.mod_compat_vr.ShadersHelper; import java.awt.*; -import java.io.File; +import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.*; import java.util.function.Supplier; @@ -45,7 +44,7 @@ public class VRSettings { public static final int VERSION = 2; public static final Logger logger = LoggerFactory.getLogger("Vivecraft"); public static VRSettings inst; - public JsonObject defaults = new JsonObject(); + public static final int UNKNOWN_VERSION = 0; public static final String DEGREE = "\u00b0"; @@ -491,25 +490,25 @@ public enum UpdateType implements OptionEnum { // This map is only here to preserve old settings, not intended for general use private Map preservedSettingMap; - private final Minecraft mc; + private final File vrCfgFile; + + // holds the default settings during runtime + public JsonObject defaultsJson = new JsonObject(); + public Map defaultsMap; + private static final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + + public VRSettings() { + vrCfgFile = Xplat.getConfigPath("vivecraft-client-config.json").toFile(); - public VRSettings(Minecraft minecraft, File dataDir) { // Need to do this in the instance because array sizes aren't known until instantiation initializeFieldInfo(); // Assumes GameSettings (and hence optifine's settings) have been read first - - mc = minecraft; inst = this; // Store our class defaults to a member variable for later use storeDefaults(); - // Legacy config files. Note that in general these files will be by-passed - // by the Profile handling in ProfileManager. loadOptions and saveOptions ill - // be redirected to the profile manager using ProfileReader and ProfileWriter - // respectively. - // Load settings from the file this.loadOptions(); @@ -517,32 +516,37 @@ public VRSettings(Minecraft minecraft, File dataDir) { VRHotkeys.loadExternalCameraConfig(); } + /** + * checks which settings are defined with the {@link SettingField} annotation + */ private void initializeFieldInfo() { try { for (Field field : VRSettings.class.getFields()) { SettingField ann = field.getAnnotation(SettingField.class); - if (ann == null) { - continue; - } + if (ann != null) { + + String config = ann.config().isEmpty() ? field.getName() : ann.config(); - String config = ann.config().isEmpty() ? field.getName() : ann.config(); - ConfigEntry configEntry = new ConfigEntry(field, ann.value(), config, ann.separate(), ann.fixedSize()); - if (ann.value() != VrOptions.DUMMY) { - if (fieldEnumMap.containsKey(ann.value())) { - throw new RuntimeException("duplicate enum in setting field: " + field.getName()); + ConfigEntry configEntry = new ConfigEntry(field, ann.value(), config, ann.separate(), + ann.fixedSize()); + if (ann.value() != VrOptions.DUMMY) { + if (fieldEnumMap.containsKey(ann.value())) { + throw new RuntimeException("duplicate enum in setting field: " + field.getName()); + } + fieldEnumMap.put(ann.value(), configEntry); } - fieldEnumMap.put(ann.value(), configEntry); - } - if (ann.separate() && field.getType().isArray()) { - int len = Array.getLength(field.get(this)); - IntStream.range(0, len).forEach(i -> fieldConfigMap.put(config + "_" + i, configEntry)); - } else if (ann.separate() && Quaternion.class.isAssignableFrom(field.getType())) { - Stream.of('W', 'X', 'Y', 'Z').forEach(suffix -> fieldConfigMap.put(config + suffix, configEntry)); - } else if (ann.separate() && Vector3.class.isAssignableFrom(field.getType())) { - Stream.of('X', 'Y', 'Z').forEach(suffix -> fieldConfigMap.put(config + suffix, configEntry)); - } else { - fieldConfigMap.put(config, configEntry); + if (ann.separate() && field.getType().isArray()) { + int len = Array.getLength(field.get(this)); + IntStream.range(0, len).forEach(i -> fieldConfigMap.put(config + "_" + i, configEntry)); + } else if (ann.separate() && Quaternion.class.isAssignableFrom(field.getType())) { + Stream.of('W', 'X', 'Y', 'Z') + .forEach(suffix -> fieldConfigMap.put(config + suffix, configEntry)); + } else if (ann.separate() && Vector3.class.isAssignableFrom(field.getType())) { + Stream.of('X', 'Y', 'Z').forEach(suffix -> fieldConfigMap.put(config + suffix, configEntry)); + } else { + fieldConfigMap.put(config, configEntry); + } } } } catch (ReflectiveOperationException ex) { @@ -550,7 +554,21 @@ private void initializeFieldInfo() { } } - private Object loadOption(String name, String value, Object currentValue, VrOptions option, Class type, boolean separate) throws ReflectiveOperationException { + /** + * parses {@code value} into an Object of type {@code type} + * @param name name of the stored setting, used to correctly parse multi component settings + * @param value value as a String to parse + * @param currentValue for multi component settings this holds the object to update + * @param option option for custom handling + * @param type target type of the setting + * @param separate if multi component types are stored in individual strings, or a comma separated string + * @return parsed setting + * @throws ReflectiveOperationException if an error happens parsing the value of an Enum type option + */ + private Object loadOption( + String name, String value, Object currentValue, VrOptions option, Class type, + boolean separate) throws ReflectiveOperationException + { // First try to convert the option from a legacy value Object obj = option.convertOption(value); // If that got nothing, try the custom handler @@ -614,10 +632,19 @@ private Object loadOption(String name, String value, Object currentValue, VrOpti } // If we get here, the value wasn't interpreted - logger.warn("Don't know how to load VR option " + name + " with type " + type.getSimpleName()); + logger.warn("Don't know how to load VR option {} with type {}", name, type.getSimpleName()); return null; } + /** + * saves the value of {@code obj} to a string + * @param name name of the setting to store, is used to identify the component when {@code separate}is true + * @param obj settings value to store + * @param option option to check for a custom storage string + * @param type type of {@code obj} + * @param separate if multi component settings should be separated by component or one comma separated string + * @return String to save the value as + */ private String saveOption(String name, Object obj, VrOptions option, Class type, boolean separate) { // Try the custom handler first String value = option.saveOption(obj); @@ -628,7 +655,9 @@ private String saveOption(String name, Object obj, VrOptions option, Class ty // Generic handlers if (type == String.class) { return (String) obj; - } else if (type == Boolean.TYPE || type == Integer.TYPE || type == Long.TYPE || type == Float.TYPE || type == Double.TYPE) { + } else if (type == Boolean.TYPE || type == Integer.TYPE || type == Long.TYPE || type == Float.TYPE || + type == Double.TYPE) + { return obj.toString(); } else if (type.isEnum()) { return ((Enum) obj).name(); @@ -664,9 +693,23 @@ private String saveOption(String name, Object obj, VrOptions option, Class ty return null; } - private Object loadDefault(String name, String value, VrOptions option, Class type, boolean separate, Map profileSet) throws ReflectiveOperationException { + /** + * loads the default value of the setting with the given {@code name} + * @param name name of the setting to load + * @param value value to load/parse, if null it gets retrieved from the {@code settingsMap} + * @param option option to check for a custom default value + * @param type object type of the setting + * @param separate if multi component types are stored in individual strings, or a comma separated string + * @param settingsMap map of settings to get the default from + * @return default value of the setting with the given {@code name} + * @throws ReflectiveOperationException if an error happens reading the default of an Enum type option + */ + private Object loadDefault( + String name, String value, VrOptions option, Class type, boolean separate, + Map settingsMap) throws ReflectiveOperationException + { if (value == null) { - value = profileSet.get(name); + value = settingsMap.get(name); } // Try the custom handler first @@ -695,7 +738,7 @@ private Object loadDefault(String name, String value, VrOptions option, Class Quaternion quat = new Quaternion(); if (separate) { Stream.of('W', 'X', 'Y', 'Z').forEach(suffix -> { - String str = profileSet.get(name + suffix); + String str = settingsMap.get(name + suffix); float f = Float.parseFloat(str); switch (suffix) { case 'W' -> quat.w = f; @@ -716,7 +759,7 @@ private Object loadDefault(String name, String value, VrOptions option, Class Vector3 vec = new Vector3(); if (separate) { Stream.of('X', 'Y', 'Z').forEach(suffix -> { - String str = profileSet.get(name + suffix); + String str = settingsMap.get(name + suffix); float f = Float.parseFloat(str); switch (suffix) { case 'X' -> vec.x = f; @@ -734,14 +777,16 @@ private Object loadDefault(String name, String value, VrOptions option, Class } // If we get here, the value wasn't interpreted - logger.warn("Don't know how to load default VR option " + name + " with type " + type.getSimpleName()); + logger.warn("Don't know how to load default VR option {} with type {}", name, type.getSimpleName()); return null; } + /** + * resets the given setting to its default value + * @param option setting to reset + */ public void loadDefault(VrOptions option) { - if (this.defaults == null) { - return; // how - } + if (this.defaultsMap == null) return; // how try { var mapping = fieldEnumMap.get(option); @@ -752,26 +797,27 @@ public void loadDefault(VrOptions option) { Class type = field.getType(); String name = mapping.configName; - Map profileSet = ProfileManager.getProfileSet(this.defaults, ProfileManager.PROFILE_SET_VR); - if (type.isArray()) { Object arr = field.get(this); int len = Array.getLength(arr); if (mapping.separate) { for (int i = 0; i < len; i++) { - Object obj = Objects.requireNonNull(loadDefault(name + "_" + i, null, option, type.getComponentType(), false, profileSet)); + Object obj = Objects.requireNonNull( + loadDefault(name + "_" + i, null, option, type.getComponentType(), false, defaultsMap)); Array.set(arr, i, obj); } } else { - String str = profileSet.get(name); + String str = defaultsMap.get(name); String[] split = str.split(";", -1); // Avoid conflicting with other comma-delimited types for (int i = 0; i < len; i++) { - Object obj = Objects.requireNonNull(loadDefault(name, split[i], option, type.getComponentType(), false, profileSet)); + Object obj = Objects.requireNonNull( + loadDefault(name, split[i], option, type.getComponentType(), false, defaultsMap)); Array.set(arr, i, obj); } } } else { - Object obj = Objects.requireNonNull(loadDefault(name, null, option, type, mapping.separate, profileSet)); + Object obj = Objects.requireNonNull( + loadDefault(name, null, option, type, mapping.separate, defaultsMap)); field.set(this, obj); } } catch (Exception ex) { @@ -780,87 +826,148 @@ public void loadDefault(VrOptions option) { } } - public void loadOptions() { - loadOptions(null); - } + /** + * reads the config json and stores its contents in a map + * @return map contain in stored contents + */ + private Map loadSettingsFile() { + Map data = new HashMap<>(); + try { + File legacyFile = null; + if (!vrCfgFile.exists()) { + vrCfgFile.createNewFile(); + // check if there is a legacy file + VRSettings.logger.info("Checking for legacy vivecraft settings File."); + legacyFile = new File(Minecraft.getInstance().gameDirectory, "optionsviveprofiles.txt"); + } - public void loadDefaults() { - loadOptions(this.defaults); + InputStreamReader inputstreamreader = new InputStreamReader( + new FileInputStream(legacyFile == null ? vrCfgFile : legacyFile), StandardCharsets.UTF_8); + + JsonObject currentConfig; + try { + currentConfig = JsonParser.parseReader(inputstreamreader).getAsJsonObject(); + } catch (Exception exception) { + currentConfig = new JsonObject(); + } + + inputstreamreader.close(); + + // check for legacy settings + if (legacyFile != null && currentConfig.has("Profiles")) { + currentConfig = currentConfig + .getAsJsonObject("Profiles") + .getAsJsonObject("Default") + .getAsJsonObject("Vr"); + } + + for (String key : currentConfig.keySet()) { + data.put(key, currentConfig.get(key).getAsString()); + } + } catch (Exception exception1) { + VRSettings.logger.error("FAILED to read Vivecraft settings!"); + exception1.printStackTrace(); + } + return data; } - public void loadOptions(JsonObject theProfiles) { - // Load Minecrift options - try { - ProfileReader optionsVRReader = new ProfileReader(ProfileManager.PROFILE_SET_VR, theProfiles); + /** + * loads the settings from the config file + */ + public void loadOptions() { + Map settings = loadSettingsFile(); - String var2 = ""; + for (Map.Entry entry : settings.entrySet()) { + String name = entry.getKey(); + String value = entry.getValue() != null ? entry.getValue() : ""; + try { + var mapping = fieldConfigMap.get(name); - while ((var2 = optionsVRReader.readLine()) != null) { - try { - String[] optionTokens = var2.split(":", 2); - String name = optionTokens[0]; - String value = optionTokens.length > 1 ? optionTokens[1] : ""; + if (mapping == null) continue; - var mapping = fieldConfigMap.get(name); - if (mapping == null) { - continue; - } + Field field = mapping.field; + Class type = field.getType(); + Object currentValue = field.get(this); - Field field = mapping.field; - Class type = field.getType(); - Object currentValue = field.get(this); - if (type.isArray()) { - if (mapping.separate) { - int index = Integer.parseInt(name.substring(name.lastIndexOf('_') + 1)); - Object obj = Objects.requireNonNull(loadOption(name.substring(0, name.lastIndexOf('_')), value, Array.get(currentValue, index), mapping.vrOptions, type.getComponentType(), false)); - Array.set(currentValue, index, obj); - } else { - int len = Array.getLength(currentValue); - String[] split = value.split(";", -1); // Avoid conflicting with other comma-delimited types - if (split.length != len && !mapping.fixedSize) { - Object newValue = Array.newInstance(type.getComponentType(), split.length); - System.arraycopy(currentValue, 0, newValue, 0, Math.min(len, split.length)); - field.set(this, newValue); - currentValue = newValue; - len = split.length; - } - for (int i = 0; i < len; i++) { - Object obj = Objects.requireNonNull(loadOption(name, split[i], Array.get(currentValue, i), mapping.vrOptions, type.getComponentType(), false)); - Array.set(currentValue, i, obj); - } - } + if (type.isArray()) { + if (mapping.separate) { + int index = Integer.parseInt(name.substring(name.lastIndexOf('_') + 1)); + + Object obj = Objects.requireNonNull( + loadOption(name.substring(0, name.lastIndexOf('_')), value, Array.get(currentValue, index), + mapping.vrOption, type.getComponentType(), false)); + Array.set(currentValue, index, obj); } else { - Object obj = Objects.requireNonNull(loadOption(name, value, currentValue, mapping.vrOptions, type, mapping.separate)); - field.set(this, obj); + int len = Array.getLength(currentValue); + String[] split = value.split(";", -1); // Avoid conflicting with other comma-delimited types + if (split.length != len && !mapping.fixedSize) { + Object newValue = Array.newInstance(type.getComponentType(), split.length); + System.arraycopy(currentValue, 0, newValue, 0, Math.min(len, split.length)); + field.set(this, newValue); + currentValue = newValue; + len = split.length; + } + for (int i = 0; i < len; i++) { + Object obj = Objects.requireNonNull( + loadOption(name, split[i], Array.get(currentValue, i), mapping.vrOption, + type.getComponentType(), false)); + Array.set(currentValue, i, obj); + } } - } catch (Exception var7) { - logger.warn("Skipping bad VR option: " + var2); - var7.printStackTrace(); + } else { + Object obj = Objects.requireNonNull( + loadOption(name, value, currentValue, mapping.vrOption, type, mapping.separate)); + field.set(this, obj); } + } catch (Exception exception) { + logger.warn("Skipping bad VR option: {}:{}", name, value); + exception.printStackTrace(); } - - preservedSettingMap = optionsVRReader.getData(); - optionsVRReader.close(); - } catch (Exception var8) { - logger.warn("Failed to load VR options!"); - var8.printStackTrace(); } + + preservedSettingMap = settings; } - public void saveOptions() { - saveOptions(null); // Use null for current profile + /** + * saves the current settings to disk + */ + public synchronized void saveOptions() { + JsonObject jsonStorage = new JsonObject(); + saveOptions(jsonStorage); + try { + OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(vrCfgFile), StandardCharsets.UTF_8); + writer.write(gson.toJson(jsonStorage)); + writer.flush(); + writer.close(); + } catch (IOException ioException) { + logger.error("Failed to save VR options to disk"); + ioException.printStackTrace(); + } } - private void storeDefaults() { - saveOptions(this.defaults); + /** + * stores teh current settings in the {@code defaults} JsonObject + */ + private synchronized void storeDefaults() { + saveOptions(this.defaultsJson); + // this is a bit stupid + defaultsMap = new HashMap<>(); + for (String key : this.defaultsJson.keySet()) { + defaultsMap.put(key, this.defaultsJson.get(key).getAsString()); + } } - private void saveOptions(JsonObject theProfiles) { - // Save Minecrift settings + /** + * writes the options to the given JsonObject + * + * @param configStorage options are stored in this + */ + private void saveOptions(JsonObject configStorage) { try { - ProfileWriter var5 = new ProfileWriter(ProfileManager.PROFILE_SET_VR, theProfiles); + Map data = new HashMap<>(); + if (preservedSettingMap != null) { - var5.setData(preservedSettingMap); + data = preservedSettingMap; } for (var entry : fieldConfigMap.entrySet()) { @@ -874,127 +981,141 @@ private void saveOptions(JsonObject theProfiles) { if (type.isArray()) { if (mapping.separate) { int index = Integer.parseInt(name.substring(name.lastIndexOf('_') + 1)); - String value = Objects.requireNonNull(saveOption(name.substring(0, name.lastIndexOf('_')), Array.get(obj, index), mapping.vrOptions, type.getComponentType(), mapping.separate)); - var5.println(name + ":" + value); + String value = Objects.requireNonNull( + saveOption(name.substring(0, name.lastIndexOf('_')), Array.get(obj, index), + mapping.vrOption, type.getComponentType(), mapping.separate)); + data.put(name, value); } else { StringJoiner joiner = new StringJoiner(";"); int len = Array.getLength(obj); for (int i = 0; i < len; i++) { - String value = Objects.requireNonNull(saveOption(name, Array.get(obj, i), mapping.vrOptions, type.getComponentType(), mapping.separate)); + String value = Objects.requireNonNull( + saveOption(name, Array.get(obj, i), mapping.vrOption, type.getComponentType(), + mapping.separate)); joiner.add(value); } - var5.println(name + ":" + joiner); + data.put(name, joiner.toString()); } } else { - String value = Objects.requireNonNull(saveOption(name, obj, mapping.vrOptions, type, mapping.separate)); - var5.println(name + ":" + value); + String value = Objects.requireNonNull( + saveOption(name, obj, mapping.vrOption, type, mapping.separate)); + data.put(name, value); } } catch (Exception ex) { - logger.warn("Failed to save VR option: " + name); + logger.error("Failed to save VR option: {}", name); ex.printStackTrace(); } } - var5.close(); - } catch (Exception var3) { - logger.warn("Failed to save VR options: " + var3.getMessage()); - var3.printStackTrace(); + // add all to the json + data.forEach((key, value) -> configStorage.add(key, new JsonPrimitive(value))); + } catch (Exception exception) { + logger.error("Failed to save VR options: {}", exception.getMessage()); + exception.printStackTrace(); } } - public void resetSettings() { - // Get the Minecrift defaults - loadDefaults(); - } - - public String getButtonDisplayString(VrOptions par1EnumOptions) { - return getButtonDisplayString(par1EnumOptions, false); + /** + * convenience method to get the display string with option name + */ + public String getButtonDisplayString(VrOptions vrOption) { + return getButtonDisplayString(vrOption, false); } - public String getButtonDisplayString(VrOptions par1EnumOptions, boolean valueOnly) { - String var2 = I18n.get("vivecraft.options." + par1EnumOptions.name()); - - String var3 = var2 + ": "; - String var4 = var3; - String var5; + /** + * constructs the display string, of label and value. optionally only the value + * + * @param vrOption option to get the string for + * @param valueOnly of only the value should be in the string + * @return string containing name and value of the option + */ + public String getButtonDisplayString(VrOptions vrOption, boolean valueOnly) { + String name = I18n.get("vivecraft.options." + vrOption.name()); - if (valueOnly) { - var4 = ""; - } + String label = valueOnly ? "" : name + ": "; try { - var mapping = fieldEnumMap.get(par1EnumOptions); + var mapping = fieldEnumMap.get(vrOption); if (mapping == null) { - return var2; + return name; } + Field field = mapping.field; Class type = field.getType(); Object obj = field.get(this); - if (overrides.hasSetting(par1EnumOptions)) { - obj = this.overrides.getSetting(par1EnumOptions).getValue(); + if (overrides.hasSetting(vrOption)) { + obj = this.overrides.getSetting(vrOption).getValue(); } - String str = par1EnumOptions.getDisplayString(var4, obj); + String str = vrOption.getDisplayString(label, obj); if (str != null) { return str; } else if (type == Boolean.TYPE) { - var langKeys = par1EnumOptions.getBooleanLangKeys(); - return (boolean) obj ? var4 + I18n.get(langKeys.getLeft()) : var4 + I18n.get(langKeys.getRight()); + var langKeys = vrOption.getBooleanLangKeys(); + return (boolean) obj ? label + I18n.get(langKeys.getLeft()) : label + I18n.get(langKeys.getRight()); } else if (type == Float.TYPE || type == Double.TYPE) { - if (par1EnumOptions.getDecimalPlaces() < 0) { - return var4 + Math.round(((Number) obj).floatValue() * 100) + "%"; + if (vrOption.getDecimalPlaces() < 0) { + return label + Math.round(((Number) obj).floatValue() * 100) + "%"; } else { - return var4 + String.format("%." + par1EnumOptions.getDecimalPlaces() + "f", ((Number) obj).floatValue()); + return label + String.format("%." + vrOption.getDecimalPlaces() + "f", ((Number) obj).floatValue()); } } else if (OptionEnum.class.isAssignableFrom(type)) { - return var4 + I18n.get(((OptionEnum) obj).getLangKey()); + return label + I18n.get(((OptionEnum) obj).getLangKey()); } else { - return var4 + obj.toString(); + return label + obj.toString(); } } catch (Exception ex) { - System.out.println("Failed to get VR option display string: " + par1EnumOptions); + logger.error("Failed to get VR option display string: {}", vrOption); ex.printStackTrace(); } - return var2; + return name; } - public float getOptionFloatValue(VrOptions par1EnumOptions) { + /** + * gets the float value of the option, wiht server overrides accounted for + * + * @param vrOption option to get + * @return value of the option, or 0 if unknown + */ + public float getOptionFloatValue(VrOptions vrOption) { try { - var mapping = fieldEnumMap.get(par1EnumOptions); + var mapping = fieldEnumMap.get(vrOption); if (mapping == null) { - return 0; + return 0.0F; } + Field field = mapping.field; float value = ((Number) field.get(this)).floatValue(); - if (overrides.hasSetting(par1EnumOptions)) { - value = overrides.getSetting(par1EnumOptions).getFloat(); + if (overrides.hasSetting(vrOption)) { + value = overrides.getSetting(vrOption).getFloat(); } - return Objects.requireNonNullElse(par1EnumOptions.getOptionFloatValue(value), value); + return Objects.requireNonNullElse(vrOption.getOptionFloatValue(value), value); } catch (Exception ex) { - System.out.println("Failed to get VR option float value: " + par1EnumOptions); + logger.error("Failed to get VR option float value: {}", vrOption); ex.printStackTrace(); } - return 0.0f; + return 0.0F; } /** * For non-float options. Toggles the option on/off, or cycles through the list i.e. render distances. + * + * @param vrOption option to toggle */ - public void setOptionValue(VrOptions par1EnumOptions) { + public void setOptionValue(VrOptions vrOption) { try { - var mapping = fieldEnumMap.get(par1EnumOptions); - if (mapping == null) { - return; - } + var mapping = fieldEnumMap.get(vrOption); + if (mapping == null) return; + Field field = mapping.field; Class type = field.getType(); - Object obj = par1EnumOptions.setOptionValue(field.get(this)); + Object obj = vrOption.setOptionValue(field.get(this)); if (obj != null) { field.set(this, obj); } else if (type == Boolean.TYPE) { @@ -1002,64 +1123,56 @@ public void setOptionValue(VrOptions par1EnumOptions) { } else if (OptionEnum.class.isAssignableFrom(type)) { field.set(this, ((OptionEnum) field.get(this)).getNext()); } else { - logger.warn("Don't know how to set VR option " + mapping.configName + " with type " + type.getSimpleName()); + logger.warn("Don't know how to set VR option {} with type {}", mapping.configName, + type.getSimpleName()); return; } - par1EnumOptions.onOptionChange(); + vrOption.onOptionChange(); this.saveOptions(); } catch (Exception ex) { - System.out.println("Failed to set VR option: " + par1EnumOptions); + logger.error("Failed to set VR option: {}", vrOption); ex.printStackTrace(); } } - public void setOptionFloatValue(VrOptions par1EnumOptions, float par2) { + /** + * For float options, accounts for server override limits when setting the value + * + * @param vrOption option to set + * @param newValue new value that wants to be set + */ + public void setOptionFloatValue(VrOptions vrOption, float newValue) { try { - var mapping = fieldEnumMap.get(par1EnumOptions); - if (mapping == null) { - return; - } + var mapping = fieldEnumMap.get(vrOption); + if (mapping == null) return; + Field field = mapping.field; Class type = field.getType(); - float f = Objects.requireNonNullElse(par1EnumOptions.setOptionFloatValue(par2), par2); - if (overrides.hasSetting(par1EnumOptions)) { - f = Mth.clamp(f, overrides.getSetting(par1EnumOptions).getValueMin(), overrides.getSetting(par1EnumOptions).getValueMax()); + float actualValue = Objects.requireNonNullElse(vrOption.setOptionFloatValue(newValue), newValue); + if (overrides.hasSetting(vrOption)) { + actualValue = Mth.clamp(actualValue, overrides.getSetting(vrOption).getValueMin(), + overrides.getSetting(vrOption).getValueMax()); } if (type == Integer.TYPE) { - field.set(this, (int) f); + field.set(this, (int) actualValue); } else if (type == Long.TYPE) { - field.set(this, (long) f); + field.set(this, (long) actualValue); } else { - field.set(this, f); + field.set(this, actualValue); } - par1EnumOptions.onOptionChange(); + vrOption.onOptionChange(); this.saveOptions(); } catch (Exception ex) { - System.out.println("Failed to set VR option float value: " + par1EnumOptions); + logger.error("Failed to set VR option float value: {}", vrOption); ex.printStackTrace(); } } - /** - * Parses a string into a float. - */ - private float parseFloat(String par1Str) { - return par1Str.equals("true") ? 1.0F : (par1Str.equals("false") ? 0.0F : Float.parseFloat(par1Str)); - } - - public float getHeadTrackSensitivity() { - //if (this.useQuaternions) - return 1.0f; - - //return this.headTrackSensitivity; // TODO: If head track sensitivity is working again... if - } - - record ConfigEntry(Field field, VrOptions vrOptions, String configName, boolean separate, boolean fixedSize) { - } + record ConfigEntry(Field field, VrOptions vrOption, String configName, boolean separate, boolean fixedSize) {} public enum VrOptions { DUMMY(false, true), // Dummy @@ -1118,7 +1231,8 @@ String saveOption(Object value) { @Override String getDisplayString(String prefix, Object value) { - return Minecraft.getInstance().options.hideGui ? prefix + LangHelper.getYes() : prefix + LangHelper.getNo(); + return Minecraft.getInstance().options.hideGui ? prefix + LangHelper.getYes() : + prefix + LangHelper.getNo(); } @Override @@ -1129,7 +1243,8 @@ Object setOptionValue(Object value) { }, RENDER_MENU_BACKGROUND(false, true), // HUD/GUI Background HUD_OCCLUSION(false, true), // HUD Occlusion - MENU_ALWAYS_FOLLOW_FACE(false, true, "vivecraft.options.always", "vivecraft.options.seated"), // Main Menu Follow + MENU_ALWAYS_FOLLOW_FACE(false, true, "vivecraft.options.always", + "vivecraft.options.seated"), // Main Menu Follow CROSSHAIR_OCCLUSION(false, true), // Crosshair Occlusion CROSSHAIR_SCALE(true, false, 0.25f, 1.0f, 0.01f, -1), // Crosshair Size MENU_CROSSHAIR_SCALE(true, false, 0.25f, 2.5f, 0.05f, -1), // Menu Crosshair Size @@ -1203,12 +1318,14 @@ Object convertOption(String value) { AUTO_OPEN_KEYBOARD(false, true), // Always Open Keyboard AUTO_CLOSE_KEYBOARD(false, true), // Close Keyboard on Screenchange RADIAL_MODE_HOLD(false, true, "vivecraft.options.hold", "vivecraft.options.press"), // Radial Menu Mode - PHYSICAL_KEYBOARD(false, true, "vivecraft.options.keyboard.physical", "vivecraft.options.keyboard.pointer"), // Keyboard Type + PHYSICAL_KEYBOARD(false, true, "vivecraft.options.keyboard.physical", + "vivecraft.options.keyboard.pointer"), // Keyboard Type PHYSICAL_KEYBOARD_SCALE(true, false, 0.75f, 1.5f, 0.01f, -1) { // Keyboard Size @Override void onOptionChange() { - KeyboardHandler.physicalKeyboard.setScale(ClientDataHolderVR.getInstance().vrSettings.physicalKeyboardScale); + KeyboardHandler.physicalKeyboard.setScale( + ClientDataHolderVR.getInstance().vrSettings.physicalKeyboardScale); } }, PHYSICAL_KEYBOARD_THEME(false, false), // Keyboard Theme @@ -1241,7 +1358,8 @@ void onOptionChange() { HUD_MAX_GUI_SCALE(false, true), // force HUD to render with max GUI scale VR_TOGGLE_BUTTON_VISIBLE(false, true), // toggle in main menu VR_SETTINGS_BUTTON_VISIBLE(false, true), // setting button in options - VR_SETTINGS_BUTTON_POSITION(false, true, "vivecraft.options.left", "vivecraft.options.right"), // setting button position + VR_SETTINGS_BUTTON_POSITION(false, true, "vivecraft.options.left", + "vivecraft.options.right"), // setting button position //HMD/render FSAA(false, true), // Lanczos Scaler LOW_HEALTH_INDICATOR(false, true), // red low health pulse @@ -1300,7 +1418,8 @@ String getDisplayString(String prefix, Object value) { String getDisplayString(String prefix, Object value) { Color color = (Color) value; var p = colors.stream().filter(c -> c.getLeft().equals(color)).findFirst().orElse(null); - return p != null ? prefix + I18n.get(p.getRight()) : prefix + color.getRed() + " " + color.getGreen() + " " + color.getBlue(); + return p != null ? prefix + I18n.get(p.getRight()) : + prefix + color.getRed() + " " + color.getGreen() + " " + color.getBlue(); } @Override @@ -1317,8 +1436,10 @@ String saveOption(Object value) { @Override Object setOptionValue(Object value) { - int index = IntStream.range(0, colors.size()).filter(i -> colors.get(i).getLeft().equals(value)).findFirst().orElse(-1); - return index == -1 || index == colors.size() - 1 ? colors.get(0).getLeft() : colors.get(index + 1).getLeft(); + int index = IntStream.range(0, colors.size()).filter(i -> colors.get(i).getLeft().equals(value)) + .findFirst().orElse(-1); + return index == -1 || index == colors.size() - 1 ? colors.get(0).getLeft() : + colors.get(index + 1).getLeft(); } }, MIXED_REALITY_RENDER_HANDS(false, true), // Show Hands @@ -1483,7 +1604,8 @@ Float setOptionFloatValue(float value) { void onOptionChange() { if (VRState.vrRunning) { ClientDataHolderVR.getInstance().vrPlayer.roomScaleMovementDelay = 2; - ClientDataHolderVR.getInstance().vrPlayer.snapRoomOriginToPlayerEntity(Minecraft.getInstance().player, false, true); + ClientDataHolderVR.getInstance().vrPlayer.snapRoomOriginToPlayerEntity( + Minecraft.getInstance().player, false, true); VRPlayer.get().preTick(); } } @@ -1570,7 +1692,9 @@ void onOptionChange() { String getDisplayString(String prefix, Object value) { if (VRState.vrEnabled) { RenderTarget eye0 = ClientDataHolderVR.getInstance().vrRenderer.framebufferEye0; - return prefix + Math.round((float) value * 100) + "% (" + (int) Math.ceil(eye0.viewWidth * Math.sqrt((float) value)) + "x" + (int) Math.ceil(eye0.viewHeight * Math.sqrt((float) value)) + ")"; + return prefix + Math.round((float) value * 100) + "% (" + + (int) Math.ceil(eye0.viewWidth * Math.sqrt((float) value)) + "x" + + (int) Math.ceil(eye0.viewHeight * Math.sqrt((float) value)) + ")"; } else { return prefix + Math.round((float) value * 100) + "%"; } @@ -1708,21 +1832,24 @@ Object convertOption(String value) { @Override String getDisplayString(String prefix, Object value) { - return (int) value > 0 ? prefix + LangHelper.get("vivecraft.options.teleportlimit", value) : prefix + "OFF"; + return (int) value > 0 ? prefix + LangHelper.get("vivecraft.options.teleportlimit", value) : + prefix + "OFF"; } }, TELEPORT_UP_LIMIT(true, false, 0, 4, 1, 0) { // Up Limit @Override String getDisplayString(String prefix, Object value) { - return (int) value > 0 ? prefix + LangHelper.get("vivecraft.options.teleportlimit", value) : prefix + "OFF"; + return (int) value > 0 ? prefix + LangHelper.get("vivecraft.options.teleportlimit", value) : + prefix + "OFF"; } }, TELEPORT_HORIZ_LIMIT(true, false, 0, 32, 1, 0) { // Distance Limit @Override String getDisplayString(String prefix, Object value) { - return (int) value > 0 ? prefix + LangHelper.get("vivecraft.options.teleportlimit", value) : prefix + "OFF"; + return (int) value > 0 ? prefix + LangHelper.get("vivecraft.options.teleportlimit", value) : + prefix + "OFF"; } }, ALLOW_STANDING_ORIGIN_OFFSET(false, true, LangHelper.YES_KEY, LangHelper.NO_KEY), // Allow Origin Offset @@ -1742,7 +1869,8 @@ Object convertOption(String value) { } } }, - MENU_WORLD_FALLBACK(false, true, "vivecraft.options.menuworldfallback.panorama", "vivecraft.options.menuworldfallback.dirtbox"), // fallback for when menurwold is not shown + MENU_WORLD_FALLBACK(false, true, "vivecraft.options.menuworldfallback.panorama", + "vivecraft.options.menuworldfallback.dirtbox"), // fallback for when menurwold is not shown HRTF_SELECTION(false, false) { // HRTF // this is now handled by vanilla @@ -1759,16 +1887,8 @@ String getDisplayString(String prefix, Object value) { } }, INGAME_BINDINGS_IN_GUI(false, true), - RADIAL_NUMBER(false, false,4, 14, 2, 0), + RADIAL_NUMBER(false, false, 4, 14, 2, 0), RIGHT_CLICK_DELAY(false, false); // Right Click Repeat -// ANISOTROPIC_FILTERING("options.anisotropicFiltering", true, false, 1.0F, 16.0F, 0.0F) -// { -// private static final String __OBFID = "CL_00000654"; -// protected float snapToStep(float p_148264_1_) -// { -// return (float) MathHelper.roundUpToPowerOfTwo((int) p_148264_1_); -// } -// }, private final boolean enumFloat; private final boolean enumBoolean; @@ -1778,49 +1898,47 @@ String getDisplayString(String prefix, Object value) { private final int decimalPlaces; private final Pair booleanLangKeys; - public static VrOptions getEnumOptions(int par0) { - VrOptions[] aoptions = values(); - int j = aoptions.length; - - for (int k = 0; k < j; ++k) { - VrOptions options = aoptions[k]; - - if (options.returnEnumOrdinal() == par0) { - return options; - } - } - - return null; - } - - VrOptions(boolean isfloat, boolean isbool) { - this(isfloat, isbool, 0.0F, 1.0F, 0.0F, 0); + /** + * @param isFloat if true, creates a float setting with range 0 or 1 state + * @param isBoolean if true creates an ON/OFF setting + */ + VrOptions(boolean isFloat, boolean isBoolean) { + this(isFloat, isBoolean, 0.0F, 1.0F, 0.0F, 0); } - VrOptions(boolean isfloat, boolean isbool, String trueLangKey, String falseKangKey) { - this(isfloat, isbool, 0.0F, 1.0F, 0.0F, 0, trueLangKey, falseKangKey); + /** + * @param isFloat if true, creates a float setting with range 0 or 1 state + * @param isBoolean if true creates a boolean setting with the given lang states + * @param trueLangKey lang key for when the setting is ON + * @param falseLangKey lang key for when the setting is OFF + */ + VrOptions(boolean isFloat, boolean isBoolean, String trueLangKey, String falseLangKey) { + this(isFloat, isBoolean, 0.0F, 1.0F, 0.0F, 0, trueLangKey, falseLangKey); } /** - * @param isfloat - * @param isbool - * @param min - * @param max - * @param step + * @param isFloat if true, creates a float setting with the specified parameters + * @param isBoolean if true creates an ON/OFF setting + * @param min minimum value of the float setting + * @param max maximum value of the float setting + * @param step step size between individual setting states * @param decimalPlaces number of decimal places for float value, negative to display as percentage */ - VrOptions(boolean isfloat, boolean isbool, float min, float max, float step, int decimalPlaces) { - this(isfloat, isbool, min, max, step, decimalPlaces, LangHelper.ON_KEY, LangHelper.OFF_KEY); + VrOptions(boolean isFloat, boolean isBoolean, float min, float max, float step, int decimalPlaces) { + this(isFloat, isBoolean, min, max, step, decimalPlaces, LangHelper.ON_KEY, LangHelper.OFF_KEY); } - VrOptions(boolean isfloat, boolean isboolean, float min, float max, float step, int decimalPlaces, String trueLangKey, String falseKangKey) { - this.enumFloat = isfloat; - this.enumBoolean = isboolean; + VrOptions( + boolean isFloat, boolean isBoolean, float min, float max, float step, int decimalPlaces, String trueLangKey, + String falseLangKey) + { + this.enumFloat = isFloat; + this.enumBoolean = isBoolean; this.valueMin = min; this.valueMax = max; this.valueStep = step; this.decimalPlaces = decimalPlaces; - this.booleanLangKeys = Pair.of(trueLangKey, falseKangKey); + this.booleanLangKeys = Pair.of(trueLangKey, falseLangKey); } Object convertOption(String value) { @@ -1851,8 +1969,7 @@ Float setOptionFloatValue(float value) { return null; } - void onOptionChange() { - } + void onOptionChange() {} public boolean getEnumFloat() { return this.enumFloat; @@ -1882,156 +1999,31 @@ public Pair getBooleanLangKeys() { return booleanLangKeys; } - protected float snapToStep(float p_148264_1_) { + protected float snapToStep(float value) { if (this.valueStep > 0.0F) { - p_148264_1_ = this.valueStep * (float) Math.round(p_148264_1_ / this.valueStep); + value = this.valueStep * (float) Math.round(value / this.valueStep); } - return p_148264_1_; + return value; } public double normalizeValue(float value) { - return Mth.clamp((this.snapToStep(value) - this.valueMin) / (this.valueMax - this.valueMin), 0.0D, 1.0D); + return Mth.clamp((this.snapToStep(value) - this.valueMin) / (this.valueMax - this.valueMin), 0.0F, 1.0F); } public double denormalizeValue(float value) { - return this.snapToStep((float) (this.valueMin + (this.valueMax - this.valueMin) * Mth.clamp(value, 0.0D, 1.0D))); + return this.snapToStep(this.valueMin + (this.valueMax - this.valueMin) * Mth.clamp(value, 0.0F, 1.0F)); } } - public static synchronized void initSettings(Minecraft mc, File dataDir) { - ProfileManager.init(dataDir); - var vrSettings = new VRSettings(mc, dataDir); + public static void initSettings() { + var vrSettings = new VRSettings(); vrSettings.saveOptions(); ClientDataHolderVR.getInstance().vrSettings = vrSettings; } - public static synchronized void loadAll(Minecraft mc) { - mc.options.load(); - ClientDataHolderVR.getInstance().vrSettings.loadOptions(); - } - - public static synchronized void saveAll(Minecraft mc) { - mc.options.save(); - ClientDataHolderVR.getInstance().vrSettings.saveOptions(); - } - - public static synchronized void resetAll(Minecraft mc) { - ClientDataHolderVR.getInstance().vrSettings.resetSettings(); - } - - public static synchronized String getCurrentProfile() { - return ProfileManager.getCurrentProfileName(); - } - - public static synchronized boolean profileExists(String profile) { - return ProfileManager.profileExists(profile); - } - - public static synchronized SortedSet getProfileList() { - return ProfileManager.getProfileList(); - } - - public static synchronized boolean setCurrentProfile(String profile) { - StringBuilder error = new StringBuilder(); - return setCurrentProfile(profile, error); - } - - public static synchronized boolean setCurrentProfile(String profile, StringBuilder error) { - boolean result = true; - Minecraft mc = Minecraft.getInstance(); - - // Save settings in current profile - VRSettings.saveAll(mc); - - // Set the new profile - result = ProfileManager.setCurrentProfile(profile, error); - - if (result) { - // Load new profile - VRSettings.loadAll(mc); - } - - return result; - } - - public static synchronized boolean createProfile(String profile, boolean useDefaults, StringBuilder error) { - boolean result = true; - Minecraft mc = Minecraft.getInstance(); - String originalProfile = VRSettings.getCurrentProfile(); - - // Save settings in original profile - VRSettings.saveAll(mc); - - // Create the new profile - if (!ProfileManager.createProfile(profile, error)) { - return false; - } - - // Set the new profile - ProfileManager.setCurrentProfile(profile, error); - - // Save existing settings as new profile... - - if (useDefaults) { - // ...unless set to use defaults - VRSettings.resetAll(mc); - } - - // Save new profile settings to file - VRSettings.saveAll(mc); - - // Select the original profile - ProfileManager.setCurrentProfile(originalProfile, error); - VRSettings.loadAll(mc); - - return result; - } - - public static synchronized boolean deleteProfile(String profile) { - StringBuilder error = new StringBuilder(); - return deleteProfile(profile, error); - } - - public static synchronized boolean deleteProfile(String profile, StringBuilder error) { - Minecraft mc = Minecraft.getInstance(); - - // Save settings in current profile - VRSettings.saveAll(mc); - - // Nuke the profile data - if (!ProfileManager.deleteProfile(profile, error)) { - return false; - } - - // Load settings in case the selected profile has changed - VRSettings.loadAll(mc); - - return true; - } - - public static synchronized boolean duplicateProfile(String originalProfile, String newProfile, StringBuilder error) { - Minecraft mc = Minecraft.getInstance(); - - // Save settings in current profile - VRSettings.saveAll(mc); - - // Duplicate the profile data - return ProfileManager.duplicateProfile(originalProfile, newProfile, error); - } - - public static synchronized boolean renameProfile(String originalProfile, String newProfile, StringBuilder error) { - Minecraft mc = Minecraft.getInstance(); - - // Save settings in current profile - VRSettings.saveAll(mc); - - // Rename the profile - return ProfileManager.renameProfile(originalProfile, newProfile, error); - } - public String[] getQuickCommandsDefaults() { String[] out = new String[12]; @@ -2137,11 +2129,6 @@ public int[] getKeyboardCodesDefault() { return out; } - public double normalizeValue(float optionFloatValue) { - // TODO Auto-generated method stub - return 0; - } - public class ServerOverrides { private final Map optionMap = new EnumMap<>(VrOptions.class); private final Map networkNameMap = new HashMap<>(); diff --git a/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileManager.java b/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileManager.java deleted file mode 100644 index 0f62eb2e0..000000000 --- a/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileManager.java +++ /dev/null @@ -1,378 +0,0 @@ -package org.vivecraft.client_vr.settings.profile; - -import com.google.gson.*; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.util.*; - - -public class ProfileManager { - public static final String DEFAULT_PROFILE = "Default"; - public static final String PROFILE_SET_OF = "Of"; - public static final String PROFILE_SET_MC = "Mc"; - public static final String PROFILE_SET_VR = "Vr"; - public static final String PROFILE_SET_CONTROLLER_BINDINGS = "Controller"; - static final String KEY_PROFILES = "Profiles"; - static final String KEY_SELECTED_PROFILE = "selectedProfile"; - static String currentProfileName = "Default"; - static File vrProfileCfgFile = null; - static JsonObject jsonConfigRoot = null; - static JsonObject profiles = null; - static final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - static boolean loaded = false; - public static final String[] DEFAULT_BINDINGS = new String[]{"key.playerlist:b:6:Button 6", "axis.updown:a:2:-:Y Rotation", "walk.forward:a:0:-:Y ", "gui.axis.leftright:a:3:-:X Rotation", "gui.axis.updown:a:2:-:Y Rotation", "key.sneak:b:9:Button 9", "gui.Left:px:-", "key.itemright:b:5:Button 5", "gui.Right:px:+", "key.left:a:1:-:X ", "gui.Select:b:0:Button 0", "key.aimcenter:b:8:Button 8", "key.pickItem:b:2:Button 2", "key.menu:b:7:Button 7", "key.attack:a:4:-:Z ", "gui.Up:py:-", "key.use:a:4:+:Z ", "axis.leftright:a:3:-:X Rotation", "gui.Down:py:+", "key.right:a:1:+:X ", "key.back:a:0:+:Y ", "key.inventory:b:3:Button 3", "key.jump:b:0:Button 0", "key.drop:b:1:Button 1", "gui.Back:b:1:Button 1", "key.itemleft:b:4:Button 4"}; - - public static synchronized void init(File dataDir) { - vrProfileCfgFile = new File(dataDir, "optionsviveprofiles.txt"); - load(); - } - - public static synchronized void load() { - try { - if (!vrProfileCfgFile.exists()) { - vrProfileCfgFile.createNewFile(); - } - - InputStreamReader inputstreamreader = new InputStreamReader(new FileInputStream(vrProfileCfgFile), StandardCharsets.UTF_8); - - try { - jsonConfigRoot = JsonParser.parseReader(inputstreamreader).getAsJsonObject(); - } catch (Exception exception) { - jsonConfigRoot = new JsonObject(); - } - - inputstreamreader.close(); - - if (jsonConfigRoot.has("selectedProfile")) { - currentProfileName = jsonConfigRoot.get("selectedProfile").getAsString(); - } else { - jsonConfigRoot.add("selectedProfile", new JsonPrimitive("Default")); - } - - if (jsonConfigRoot.has("Profiles")) { - profiles = jsonConfigRoot.get("Profiles").getAsJsonObject(); - } else { - profiles = new JsonObject(); - jsonConfigRoot.add("Profiles", profiles); - } - - if (!profiles.has("Default")) { - JsonObject JsonObject = new JsonObject(); - profiles.add("Default", JsonObject); - } - - validateProfiles(); - loaded = true; - } catch (Exception exception1) { - System.out.println("FAILED to read VR profile settings!"); - exception1.printStackTrace(); - loaded = false; - } - } - - private static void validateProfiles() throws Exception { - for (Object object : profiles.keySet()) { - String s = (String) object; - Object object1 = profiles.get(s); - - if (object1 instanceof JsonObject JsonObject) { - JsonObject JsonObject1 = null; - JsonObject JsonObject2 = null; - JsonObject JsonObject3 = null; - JsonObject JsonObject4 = null; - - for (Object object2 : JsonObject.keySet()) { - String s1 = (String) object2; - Object object3 = JsonObject.get(s1); - - if (object3 instanceof JsonObject) { - if (s1.equals("Mc")) { - JsonObject1 = (JsonObject) object3; - } - - if (s1.equals("Of")) { - JsonObject2 = (JsonObject) object3; - } - - if (s1.equals("Vr")) { - JsonObject3 = (JsonObject) object3; - } - - if (s1.equals("Controller")) { - JsonObject4 = (JsonObject) object3; - } - } - } - } - } - } - - private static synchronized boolean loadLegacySettings(File settingsFile, JsonObject theProfile, String set) throws Exception { - if (!settingsFile.exists()) { - return false; - } else { - FileReader filereader = new FileReader(settingsFile); - BufferedReader bufferedreader = new BufferedReader(filereader); - Map map = new HashMap<>(); - String s; - int i; - - for (i = 0; (s = bufferedreader.readLine()) != null; ++i) { - String[] astring = splitKeyValue(s); - String s1 = astring[0]; - String s2 = ""; - - if (astring.length > 1) { - s2 = astring[1]; - } - - map.put(s1, s2); - } - - setProfileSet(theProfile, set, map); - return i != 0; - } - } - - private static synchronized boolean loadLegacySettings(String settingStr, JsonObject theProfile, String set) throws Exception { - StringReader stringreader = new StringReader(settingStr); - BufferedReader bufferedreader = new BufferedReader(stringreader); - Map map = new HashMap<>(); - String s; - int i; - - for (i = 0; (s = bufferedreader.readLine()) != null; ++i) { - String[] astring = splitKeyValue(s); - String s1 = astring[0]; - String s2 = ""; - - if (astring.length > 1) { - s2 = astring[1]; - } - - map.put(s1, s2); - } - - setProfileSet(theProfile, set, map); - return i != 0; - } - - private static synchronized boolean loadLegacySettings(String[] settingStr, JsonObject theProfile, String set) throws Exception { - Map map = new HashMap<>(); - int i = 0; - - for (String s : settingStr) { - if (s != null) { - String[] astring = splitKeyValue(s); - String s1 = astring[0]; - String s2 = ""; - - if (astring.length > 1) { - s2 = astring[1]; - } - - map.put(s1, s2); - ++i; - } - } - - setProfileSet(theProfile, set, map); - return i != 0; - } - - public static synchronized Map getProfileSet(String profile, String set) { - Map map = new HashMap<>(); - - if (profiles.has(profile)) { - JsonObject JsonObject = profiles.get(profile).getAsJsonObject(); - - if (JsonObject.has(set)) { - JsonObject JsonObject1 = JsonObject.get(set).getAsJsonObject(); - - for (String s : JsonObject1.keySet()) { - String s1 = JsonObject1.get(s).getAsString(); - map.put(s, s1); - } - } - } - - return map; - } - - public static synchronized Map getProfileSet(JsonObject theProfile, String set) { - Map map = new HashMap<>(); - - if (theProfile.has(set)) { - JsonObject JsonObject = theProfile.get(set).getAsJsonObject(); - - for (String s : JsonObject.keySet()) { - String s1 = JsonObject.get(s).getAsString(); - map.put(s, s1); - } - } - - return map; - } - - public static synchronized void setProfileSet(String profile, String set, Map settings) { - JsonObject JsonObject = null; - JsonObject JsonObject1 = new JsonObject(); - - if (profiles.has(profile)) { - JsonObject = profiles.get(profile).getAsJsonObject(); - } else { - JsonObject = new JsonObject(); - profiles.add(profile, JsonObject); - } - - for (String s : settings.keySet()) { - String s1 = settings.get(s); - JsonObject1.add(s, new JsonPrimitive(s1)); - } - - JsonObject.remove(set); - JsonObject.add(set, JsonObject1); - } - - public static synchronized void setProfileSet(JsonObject theProfile, String set, Map settings) { - JsonObject JsonObject = new JsonObject(); - - for (String s : settings.keySet()) { - String s1 = settings.get(s); - JsonObject.add(s, new JsonPrimitive(s1)); - } - - theProfile.remove(set); - theProfile.add(set, JsonObject); - } - - public static synchronized void save() { - try { - OutputStreamWriter outputstreamwriter = new OutputStreamWriter(new FileOutputStream(vrProfileCfgFile), StandardCharsets.UTF_8); - String s = gson.toJson(jsonConfigRoot); - outputstreamwriter.write(s); - outputstreamwriter.flush(); - outputstreamwriter.close(); - } catch (IOException ioexception) { - ioexception.printStackTrace(); - } - } - - public static synchronized boolean profileExists(String profileName) { - return profiles.has(profileName); - } - - public static synchronized SortedSet getProfileList() { - Set set = profiles.keySet(); - return new TreeSet<>(set); - } - - private static JsonObject getCurrentProfile() { - if (!profiles.has(currentProfileName)) { - return null; - } else { - Object object = profiles.get(currentProfileName); - return object != null && object instanceof JsonObject ? (JsonObject) object : null; - } - } - - public static synchronized String getCurrentProfileName() { - return currentProfileName; - } - - public static synchronized boolean setCurrentProfile(String profileName, StringBuilder error) { - if (!profiles.has(profileName)) { - error.append("Profile '" + profileName + "' not found."); - return false; - } else { - currentProfileName = profileName; - jsonConfigRoot.add("selectedProfile", new JsonPrimitive(currentProfileName)); - return true; - } - } - - public static synchronized boolean createProfile(String profileName, StringBuilder error) { - if (profiles.has(profileName)) { - error.append("Profile '" + profileName + "' already exists."); - return false; - } else { - JsonObject JsonObject = new JsonObject(); - profiles.add(profileName, JsonObject); - return true; - } - } - - public static synchronized boolean renameProfile(String existingProfileName, String newProfileName, StringBuilder error) { - if (existingProfileName.equals("Default")) { - error.append("Cannot rename Default profile."); - return false; - } else if (!profiles.has(existingProfileName)) { - error.append("Profile '" + existingProfileName + "' not found."); - return false; - } else if (profiles.has(newProfileName)) { - error.append("Profile '" + newProfileName + "' already exists."); - return false; - } else { - JsonObject JsonObject = profiles.get(existingProfileName).getAsJsonObject().deepCopy(); - profiles.remove(existingProfileName); - profiles.add(newProfileName, JsonObject); - - if (existingProfileName.equals(currentProfileName)) { - setCurrentProfile(newProfileName, error); - } - - return true; - } - } - - public static synchronized boolean duplicateProfile(String profileName, String duplicateProfileName, StringBuilder error) { - if (!profiles.has(profileName)) { - error.append("Profile '" + profileName + "' not found."); - return false; - } else if (profiles.has(duplicateProfileName)) { - error.append("Profile '" + duplicateProfileName + "' already exists."); - return false; - } else { - JsonObject JsonObject = profiles.get(profileName).getAsJsonObject().deepCopy(); - profiles.add(duplicateProfileName, JsonObject); - return true; - } - } - - public static synchronized boolean deleteProfile(String profileName, StringBuilder error) { - if (profileName.equals("Default")) { - error.append("Cannot delete Default profile."); - return false; - } else if (!profiles.has(profileName)) { - error.append("Profile '" + profileName + "' not found."); - return false; - } else { - profiles.remove(profileName); - - if (profileName.equals(currentProfileName)) { - setCurrentProfile("Default", error); - } - - return true; - } - } - - public static void loadControllerDefaults() { - if (loaded) { - JsonObject JsonObject = getCurrentProfile(); - - if (JsonObject != null) { - try { - loadLegacySettings(DEFAULT_BINDINGS, JsonObject, "Controller"); - } catch (Exception exception) { - exception.printStackTrace(); - } - } - } - } - - public static String[] splitKeyValue(String s) { - return s.split(":", 2); - } -} diff --git a/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileReader.java b/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileReader.java deleted file mode 100644 index bf51c3227..000000000 --- a/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileReader.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.vivecraft.client_vr.settings.profile; - -import com.google.gson.JsonObject; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -public class ProfileReader { - private final String set; - private final String profile; - private Map currentProfile = null; - private Iterator profileSettingsIt = null; - private JsonObject theProfiles = null; - - public ProfileReader(String set) { - this.profile = ProfileManager.currentProfileName; - this.set = set; - } - - public ProfileReader(String set, JsonObject theProfiles) { - this.profile = ProfileManager.currentProfileName; - this.set = set; - this.theProfiles = theProfiles; - } - - public String readLine() throws IOException { - String s = null; - - if (this.currentProfile == null) { - if (this.theProfiles == null) { - this.currentProfile = ProfileManager.getProfileSet(this.profile, this.set); - } else { - this.currentProfile = ProfileManager.getProfileSet(this.theProfiles, this.set); - } - - this.profileSettingsIt = this.currentProfile.entrySet().iterator(); - } - - if (this.profileSettingsIt.hasNext()) { - Entry entry = (Entry) this.profileSettingsIt.next(); - String s1 = (String) entry.getKey(); - String s2 = (String) entry.getValue(); - - if (s2 == null) { - s2 = ""; - } - - s = s1 + ":" + s2; - } - - return s; - } - - public void close() { - } - - public Map getData() { - return this.currentProfile; - } -} diff --git a/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileWriter.java b/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileWriter.java deleted file mode 100644 index 030b77ae1..000000000 --- a/common/src/main/java/org/vivecraft/client_vr/settings/profile/ProfileWriter.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.vivecraft.client_vr.settings.profile; - -import com.google.gson.JsonObject; - -import java.util.HashMap; -import java.util.Map; - -public class ProfileWriter { - private final String activeProfileName; - private final String set; - private Map data = new HashMap<>(); - private JsonObject theProfile = null; - - public ProfileWriter(String set) { - this.activeProfileName = ProfileManager.currentProfileName; - this.set = set; - this.data = new HashMap<>(); - } - - public ProfileWriter(String set, JsonObject theProfile) { - this.activeProfileName = ProfileManager.currentProfileName; - this.set = set; - this.theProfile = theProfile; - this.data = new HashMap<>(); - } - - public void println(String s) { - String[] astring = ProfileManager.splitKeyValue(s); - String sa = astring[0]; - String s1 = ""; - - if (astring.length > 1) { - s1 = astring[1]; - } - - this.data.put(sa, s1); - } - - public void close() { - if (this.theProfile == null) { - ProfileManager.setProfileSet(this.activeProfileName, this.set, this.data); - ProfileManager.save(); - } else { - ProfileManager.setProfileSet(this.theProfile, this.set, this.data); - } - } - - public void setData(Map data) { - this.data = data; - } -} diff --git a/common/src/main/java/org/vivecraft/mixin/client_vr/MinecraftVRMixin.java b/common/src/main/java/org/vivecraft/mixin/client_vr/MinecraftVRMixin.java index 5eff9a9b6..aa9022082 100644 --- a/common/src/main/java/org/vivecraft/mixin/client_vr/MinecraftVRMixin.java +++ b/common/src/main/java/org/vivecraft/mixin/client_vr/MinecraftVRMixin.java @@ -218,7 +218,7 @@ public abstract class MinecraftVRMixin implements MinecraftExtension { @ModifyArg(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;setOverlay(Lnet/minecraft/client/gui/screens/Overlay;)V"), method = "", index = 0) public Overlay vivecraft$initVivecraft(Overlay overlay) { RenderPassManager.INSTANCE = new RenderPassManager((MainTarget) this.mainRenderTarget); - VRSettings.initSettings((Minecraft) (Object) this, this.gameDirectory); + VRSettings.initSettings(); new Thread(UpdateChecker::checkForUpdates, "VivecraftUpdateThread").start(); // register a resource reload listener, to reload the menu world