Add savable Config class

This commit is contained in:
msk
2023-09-18 00:28:54 -07:00
parent 879a2aa2f4
commit 74520c3e04
4 changed files with 100 additions and 3 deletions
+77
View File
@@ -0,0 +1,77 @@
using System.Windows.Markup;
using System.Xml.Linq;
using Godot;
namespace WacK.Configuration
{
/// <summary>
/// A configurable variable that saves to user://settings.cfg.
/// </summary>
public class Config<[MustBeVariant] T>
{
// --- STATICALLY-TRACKED CONFIG FILE ---
private static ConfigFile cfgFile = new();
public static readonly string cfgPath = "user://settings.cfg";
// Metadata
string section, name;
// Callback
public delegate void OnValueSet();
private OnValueSet callback;
// Stored values
public T _default { get; private set; }
private T _value;
public T Value
{
get => _value;
set
{
_value = value;
Save();
if (callback != null) callback();
}
}
static Config()
{
var err = cfgFile.Load("user://settings.cfg");
if (err != Error.Ok)
{
GD.Print("Creating new settings file...");
cfgFile.Save("user://settings.cfg");
}
}
/// <summary>
///
/// </summary>
/// <param name="section">CANNOT have spaces.</param>
/// <param name="name">CANNOT contain spaces.</param>
/// <param name="defaultValue">The value to set if not found in the settings file.</param>
public Config(string section, string name, T defaultValue, OnValueSet callback = null)
{
this.section = section;
this.name = name;
_default = defaultValue;
this.callback = callback;
Fetch();
}
private void Fetch()
{
if (!cfgFile.HasSectionKey(section, name))
{
cfgFile.SetValue(section, name, Variant.From(_default));
Save();
}
Value = cfgFile.GetValue(section, name).As<T>();
}
private void Save()
{
cfgFile.Save(cfgPath);
}
}
}
+18
View File
@@ -0,0 +1,18 @@
namespace WacK.Configuration
{
/// <summary>
/// Configuration that affects the general application.
/// </summary>
public class GameSettings
{
/// --- GRAPHICS --- ///
/// <summary>
/// Value to multiply the canvas resolution by.
/// </summary>
public static Config<float> canvasResolutionMult =
new("Graphics", "canvasResolutionMultiplier", 1f);
public static Config<bool> vsync =
new("Graphics", "vsync", true);
}
}
+4 -2
View File
@@ -9,11 +9,13 @@ namespace WacK.Configuration
/// <summary> /// <summary>
/// Scroll speed multiplier. /// Scroll speed multiplier.
/// </summary> /// </summary>
public static float playSpeedMultiplier = 2f; public static Config<float> playSpeedMultiplier =
new("PlaySettings", "playSpeedMultiplier", 2f);
/// <summary> /// <summary>
/// How much to shift song audio by in seconds. /// How much to shift song audio by in seconds.
/// </summary> /// </summary>
public static float audioOffset = 0f; public static Config<float> audioOffset =
new("PlaySettings", "audioOffset", 0f);
} }
} }
+1 -1
View File
@@ -55,7 +55,7 @@ namespace WacK.Scenes
{ {
get get
{ {
return BASE_PIXELS_PER_SECOND * PlaySettings.playSpeedMultiplier; return BASE_PIXELS_PER_SECOND * PlaySettings.playSpeedMultiplier.Value;
} }
} }