diff --git a/editor/Assets/ProjectContext.cs b/editor/Assets/ProjectContext.cs index 3aed5e7d4..ef52dadff 100644 --- a/editor/Assets/ProjectContext.cs +++ b/editor/Assets/ProjectContext.cs @@ -206,41 +206,45 @@ private static void RegisterSchemes() { s_schemes["cache://"] = CachePath; s_schemes["core://"] = CorePath; s_schemes["saved://"] = SavedPath; + s_schemes["config://"] = Path.Combine(ProjectPath, "config"); // Dynamic content database schemes derived from the project's databases list foreach (var db in Databases) s_schemes[db + "://"] = Path.Combine(ProjectPath, db); } - private static IReadOnlyList ReadDatabasesFromProject(string projectPath) { + private static TomlTable? ReadProjectTable(string projectPath, string group, string? legacyKey = null) { try { + var groupFile = Path.Combine(projectPath, "config", group + ".toml"); + if (File.Exists(groupFile)) + return TomlSerializer.Deserialize(File.ReadAllText(groupFile)); + var toastFile = Directory.EnumerateFiles(projectPath, "*.toast").FirstOrDefault(); - if (toastFile is null) return ["assets"]; + if (toastFile is null) return null; var table = TomlSerializer.Deserialize(File.ReadAllText(toastFile)); - if (table?["databases"] is TomlArray dbs) { - var list = dbs.Select(d => d?.ToString() ?? "").Where(s => s.Length > 0).ToList(); - return list.Count > 0 ? list : ["assets"]; - } + if (legacyKey is null) return table; + return table?[legacyKey] as TomlTable; } catch { // ignored } + return null; + } + + private static IReadOnlyList ReadDatabasesFromProject(string projectPath) { + if (ReadProjectTable(projectPath, "project")?["databases"] is TomlArray dbs) { + var list = dbs.Select(d => d?.ToString() ?? "").Where(s => s.Length > 0).ToList(); + return list.Count > 0 ? list : ["assets"]; + } + return ["assets"]; } private static IReadOnlyList ReadLanguagesFromProject(string projectPath) { - try { - var toastFile = Directory.EnumerateFiles(projectPath, "*.toast").FirstOrDefault(); - if (toastFile is null) return ["en"]; - - var table = TomlSerializer.Deserialize(File.ReadAllText(toastFile)); - if (table?["ui"] is TomlTable ui && ui["languages"] is TomlArray langs) { - var list = langs.Select(l => l?.ToString() ?? "").Where(s => s.Length > 0).ToList(); - return list.Count > 0 ? list : ["en"]; - } - } catch { - // ignored + if (ReadProjectTable(projectPath, "ui", "ui")?["languages"] is TomlArray langs) { + var list = langs.Select(l => l?.ToString() ?? "").Where(s => s.Length > 0).ToList(); + return list.Count > 0 ? list : ["en"]; } return ["en"]; diff --git a/editor/Engine/ToastEngine.cs b/editor/Engine/ToastEngine.cs index 121295d8a..8d46020ac 100644 --- a/editor/Engine/ToastEngine.cs +++ b/editor/Engine/ToastEngine.cs @@ -157,6 +157,8 @@ public static void SetShowDebugWindows(bool visible) { /// Overlay up in game view so the cursor stays free even under a game lock public static bool DebugOverlayOwnsCursor => IsEngineReady && toast_debug_overlay_owns_cursor() != 0; + public static bool ConsoleOpen => IsEngineReady && toast_console_is_open() != 0; + public string ProjectPath { get; } public string CorePath { get; } @@ -614,6 +616,9 @@ public static void ReloadManifest() { [LibraryImport(EngineLib)] private static partial int toast_debug_overlay_owns_cursor(); + [LibraryImport(EngineLib)] + private static partial int toast_console_is_open(); + public static void ReloadProjectSettings() { if (IsEngineReady) OnTickThread(toast_reload_project_settings); } diff --git a/editor/Engine/ToastSettings.cs b/editor/Engine/ToastSettings.cs index 43f008187..358e35bd6 100644 --- a/editor/Engine/ToastSettings.cs +++ b/editor/Engine/ToastSettings.cs @@ -5,16 +5,29 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Runtime.InteropServices; namespace editor.Engine; -/// Storage type of a setting, mirroring toast::settings::Type public enum SettingType { Bool = 0, Int = 1, Float = 2, - String = 3 + String = 3, + Vec2 = 4, + Vec3 = 5, + Vec4 = 6, + Quat = 7, + + Asset = 8 +} + +public enum SettingKind { + Normal = 0, + Advanced = 1, + Debug = 2, + User = 3 } /// One setting as the engine describes it, copied out of the native registry @@ -34,10 +47,16 @@ public sealed class SettingDescriptor { public IReadOnlyList Options { get; init; } = []; public bool RequiresRestart { get; init; } public bool Hidden { get; init; } + public SettingKind Kind { get; init; } + public bool IsArray { get; init; } + + public SettingType ValueType { get; init; } /// Non-empty turns a string setting into an asset picker of this type public string AssetType { get; init; } = string.Empty; + public string Unit { get; init; } = string.Empty; + /// Equal bounds mean the engine declared none, so the editor shows a number box rather than a slider public bool HasRange => Math.Abs(Max - Min) > double.Epsilon; @@ -58,6 +77,9 @@ internal struct ToastSettingDesc { public int optionCount; public int requiresRestart; public int hidden; + public int kind; + public int isArray; + public int valueType; } /// @@ -97,7 +119,11 @@ public static List Enumerate() { Options = options, RequiresRestart = desc.requiresRestart != 0, Hidden = desc.hidden != 0, - AssetType = Marshal.PtrToStringUTF8(toast_settings_get_asset_type(i)) ?? string.Empty + Kind = (SettingKind)desc.kind, + IsArray = desc.isArray != 0, + ValueType = (SettingType)desc.valueType, + AssetType = Marshal.PtrToStringUTF8(toast_settings_get_asset_type(i)) ?? string.Empty, + Unit = Marshal.PtrToStringUTF8(toast_settings_get_unit(i)) ?? string.Empty }); } @@ -118,13 +144,43 @@ public static string GetString(string key) { public static void SetFloat(string key, double value) => toast_settings_set_float(key, value); public static void SetString(string key, string value) => toast_settings_set_string(key, value); + public static string GetText(string key) => Read(toast_settings_get_text(key)); + + public static string GetDefaultText(string key) => Read(toast_settings_get_default_text(key)); + + public static bool SetText(string key, string text, out string error) { + var ok = toast_settings_set_text(key, text) != 0; + error = ok ? string.Empty : Read(toast_settings_last_error()); + return ok; + } + + public static double Number(string key, double fallback) { + return double.TryParse(GetText(key), NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : fallback; + } + + public static bool Flag(string key, bool fallback) { + return GetText(key) switch { + "true" => true, + "false" => false, + _ => fallback + }; + } + + public static bool IsOverridden(string key) => toast_settings_is_overridden(key) != 0; + + private static string Read(IntPtr ptr) => ptr == IntPtr.Zero ? string.Empty : Marshal.PtrToStringUTF8(ptr) ?? string.Empty; + public static void Reset(string key) => toast_settings_reset(key); public static void ResetAll() => toast_settings_reset_all(); public static bool Save() => toast_settings_save() != 0; + + public static void Restore() => toast_settings_restore(); + + public static bool Cook(string configDir, string toastFile, string stageDir) => + toast_settings_cook(configDir, toastFile, stageDir) != 0; public static bool IsDirty => toast_settings_is_dirty() != 0; - /// Where the active layer writes. The editor writes the project layer, so this is the file that ships public static string ActivePath { get { var ptr = toast_settings_active_path(); @@ -144,6 +200,9 @@ public static string ActivePath { [LibraryImport(EngineLib)] private static partial IntPtr toast_settings_get_asset_type(int index); + [LibraryImport(EngineLib)] + private static partial IntPtr toast_settings_get_unit(int index); + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] private static partial int toast_settings_get_bool(string key); @@ -170,6 +229,21 @@ public static string ActivePath { [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] private static partial void toast_settings_set_string(string key, string value); + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] + private static partial IntPtr toast_settings_get_text(string key); + + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] + private static partial IntPtr toast_settings_get_default_text(string key); + + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] + private static partial int toast_settings_set_text(string key, string text); + + [LibraryImport(EngineLib)] + private static partial IntPtr toast_settings_last_error(); + + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] + private static partial int toast_settings_is_overridden(string key); + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] private static partial void toast_settings_reset(string key); @@ -179,6 +253,12 @@ public static string ActivePath { [LibraryImport(EngineLib)] private static partial int toast_settings_save(); + [LibraryImport(EngineLib)] + private static partial void toast_settings_restore(); + + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] + private static partial int toast_settings_cook(string configDir, string toastFile, string stageDir); + [LibraryImport(EngineLib)] private static partial int toast_settings_is_dirty(); diff --git a/editor/Git/GitService.cs b/editor/Git/GitService.cs index 0ade5d8d1..1b4becd4a 100644 --- a/editor/Git/GitService.cs +++ b/editor/Git/GitService.cs @@ -11,8 +11,8 @@ namespace editor.Git; public sealed class GitService : IDisposable { - private static readonly TimeSpan s_fetchInterval = TimeSpan.FromMinutes(5); - private static readonly TimeSpan s_locksInterval = TimeSpan.FromMinutes(1); + private static TimeSpan FetchInterval => TimeSpan.FromSeconds(Math.Clamp(ToastSettings.Number("editor.git.fetch_seconds", 300), 10, 7200)); + private static TimeSpan LocksInterval => TimeSpan.FromSeconds(Math.Clamp(ToastSettings.Number("editor.git.locks_seconds", 60), 10, 600)); private sealed record StatusSnapshot( GitBranchInfo Branch, @@ -169,12 +169,12 @@ private async Task InitializeAsync() { private void StartBackgroundWork() { if (m_disposed) return; - m_fetchTimer = new DispatcherTimer { Interval = s_fetchInterval }; + m_fetchTimer = new DispatcherTimer { Interval = FetchInterval }; m_fetchTimer.Tick += (_, _) => _ = FetchAsync(); m_fetchTimer.Start(); if (HasLfs) { - m_locksTimer = new DispatcherTimer { Interval = s_locksInterval }; + m_locksTimer = new DispatcherTimer { Interval = LocksInterval }; m_locksTimer.Tick += (_, _) => _ = RefreshLocksAsync(); m_locksTimer.Start(); } diff --git a/editor/Logger/LogEntry.cs b/editor/Logger/LogEntry.cs index 67c82f7ff..fc89828de 100644 --- a/editor/Logger/LogEntry.cs +++ b/editor/Logger/LogEntry.cs @@ -6,12 +6,26 @@ using System; using System.Globalization; using System.IO; +using editor.Engine; namespace editor.Logger; public sealed class LogEntry { private const char FieldSeparator = ''; - private const int MaxDisplayMessageLength = 500; + private static int s_maxLength = 500; + private static long s_maxLengthRead; + + private static int MaxDisplayMessageLength { + get { + var now = Environment.TickCount64; + if (now - s_maxLengthRead > 2000) { + s_maxLengthRead = now; + s_maxLength = (int)Math.Clamp(ToastSettings.Number("editor.logs.max_message_length", 500), 80, 5000); + } + + return s_maxLength; + } + } public LogEntry(ulong timestampNanos, uint severity, string filepath, uint line, string sink, string message, string details = "", string backtrace = "") { diff --git a/editor/Settings/ProjectInfoViewModel.cs b/editor/Settings/ProjectInfoViewModel.cs new file mode 100644 index 000000000..901dac843 --- /dev/null +++ b/editor/Settings/ProjectInfoViewModel.cs @@ -0,0 +1,71 @@ +// +// ProjectInfoViewModel.cs by Xein +// 24 Nov 2026 +// + +using System; +using System.IO; +using System.Linq; +using CommunityToolkit.Mvvm.ComponentModel; +using editor.Assets; +using Tomlyn; +using Tomlyn.Model; + +namespace editor.Settings; + +public sealed partial class ProjectInfoViewModel : ObservableObject { + private string m_path = string.Empty; + private bool m_loading; + + [ObservableProperty] private int m_major; + [ObservableProperty] private int m_minor; + [ObservableProperty] private string m_name = string.Empty; + [ObservableProperty] private int m_patch; + [ObservableProperty] private string m_status = string.Empty; + + public bool HasProject => m_path.Length > 0; + + public void Load() { + m_path = ProjectContext.IsInitialized + ? Directory.EnumerateFiles(ProjectContext.ProjectPath, "*.toast").FirstOrDefault() ?? string.Empty + : string.Empty; + OnPropertyChanged(nameof(HasProject)); + if (m_path.Length == 0) return; + + m_loading = true; + try { + var root = TomlSerializer.Deserialize(File.ReadAllText(m_path)) ?? []; + Name = root.TryGetValue("name", out var name) ? name?.ToString() ?? string.Empty : string.Empty; + var version = root.TryGetValue("version", out var v) && v is TomlArray array ? array : null; + Major = Component(version, 0); + Minor = Component(version, 1); + Patch = Component(version, 2); + } catch (Exception e) { + Status = $"Could not read the project file: {e.Message}"; + } finally { + m_loading = false; + } + } + + private static int Component(TomlArray? array, int index) { + return array is not null && index < array.Count && array[index] is long number ? (int)Math.Clamp(number, 0, int.MaxValue) : 0; + } + + partial void OnNameChanged(string value) => Save(); + partial void OnMajorChanged(int value) => Save(); + partial void OnMinorChanged(int value) => Save(); + partial void OnPatchChanged(int value) => Save(); + + private void Save() { + if (m_loading || m_path.Length == 0) return; + try { + var root = TomlSerializer.Deserialize(File.ReadAllText(m_path)) ?? []; + root["name"] = Name; + root["version"] = new TomlArray { (long)Major, (long)Minor, (long)Patch }; + File.WriteAllText(m_path, TomlSerializer.Serialize(root)); + Status = string.Empty; + } catch (Exception e) { + Status = $"Could not write the project file: {e.Message}"; + } + } +} diff --git a/editor/Settings/SettingRows.cs b/editor/Settings/SettingRows.cs new file mode 100644 index 000000000..8e47ce843 --- /dev/null +++ b/editor/Settings/SettingRows.cs @@ -0,0 +1,381 @@ +// +// SettingRows.cs by Xein +// 24 Nov 2026 +// + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using System.Text; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using editor.Engine; + +namespace editor.Settings; + +public abstract partial class SettingRow : ObservableObject { + protected SettingRow(SettingDescriptor descriptor) { + Descriptor = descriptor; + Label = SettingsTree.LabelOf(descriptor); + m_isOverridden = ToastSettings.IsOverridden(descriptor.Key); + } + + protected bool SuppressWrite; + + [ObservableProperty] private string m_error = string.Empty; + [ObservableProperty] private bool m_isOverridden; + + public SettingDescriptor Descriptor { get; } + public string Key => Descriptor.Key; + public string Label { get; } + public bool RequiresRestart => Descriptor.RequiresRestart; + public string Unit => Descriptor.Unit; + public bool HasUnit => Descriptor.Unit.Length > 0; + public bool HasError => Error.Length > 0; + + public string Tooltip { + get { + var text = new StringBuilder(); + if (Descriptor.Description.Length > 0) text.AppendLine(Descriptor.Description); + if (Descriptor.RequiresRestart) text.AppendLine("Applies on restart"); + text.Append(Key); + return text.ToString(); + } + } + + partial void OnErrorChanged(string value) { + OnPropertyChanged(nameof(HasError)); + } + + [RelayCommand] + private void Reset() { + ToastSettings.Reset(Key); + Reload(); + } + + public void Reload(bool force = true) { + if (!force && HasError) return; + + SuppressWrite = true; + try { + ReadValue(); + Error = string.Empty; + } finally { + SuppressWrite = false; + } + + IsOverridden = ToastSettings.IsOverridden(Key); + } + + protected abstract void ReadValue(); + + protected void Written() { + IsOverridden = ToastSettings.IsOverridden(Key); + } + + public bool Matches(string query) { + return Contains(Label, query) || Contains(Key, query) || Contains(Descriptor.Description, query); + } + + private static bool Contains(string text, string query) { + return text.Contains(query, StringComparison.OrdinalIgnoreCase); + } + + public static SettingRow Create(SettingDescriptor descriptor) { + if (descriptor.IsArray) return new ArraySettingRow(descriptor); + + return descriptor.ValueType switch { + SettingType.Vec2 => new VectorSettingRow(descriptor, 2), + SettingType.Vec3 => new VectorSettingRow(descriptor, 3), + SettingType.Vec4 => new VectorSettingRow(descriptor, 4), + SettingType.Quat => new VectorSettingRow(descriptor, 4), + SettingType.Asset => new AssetSettingRow(descriptor), + _ when descriptor.IsEnum => new ChoiceSettingRow(descriptor), + SettingType.Bool => new BoolSettingRow(descriptor), + SettingType.Int => new IntSettingRow(descriptor), + SettingType.Float => new FloatSettingRow(descriptor), + _ => new TextSettingRow(descriptor) + }; + } +} + +public sealed partial class BoolSettingRow : SettingRow { + [ObservableProperty] private bool m_value; + + public BoolSettingRow(SettingDescriptor descriptor) : base(descriptor) { + m_value = ToastSettings.GetBool(descriptor.Key); + } + + partial void OnValueChanged(bool value) { + if (SuppressWrite) return; + ToastSettings.SetBool(Key, value); + Written(); + } + + protected override void ReadValue() => Value = ToastSettings.GetBool(Key); +} + +public sealed partial class IntSettingRow : SettingRow { + [ObservableProperty] private int m_value; + + public IntSettingRow(SettingDescriptor descriptor) : base(descriptor) { + m_value = (int)ToastSettings.GetInt(descriptor.Key); + } + + public double Minimum => Descriptor.HasRange ? Descriptor.Min : int.MinValue; + + public double Maximum => Descriptor.HasRange ? Descriptor.Max : int.MaxValue; + + partial void OnValueChanged(int value) { + if (SuppressWrite) return; + ToastSettings.SetInt(Key, value); + Written(); + } + + protected override void ReadValue() => Value = (int)ToastSettings.GetInt(Key); +} + +public sealed partial class FloatSettingRow : SettingRow { + [ObservableProperty] private float m_value; + + public FloatSettingRow(SettingDescriptor descriptor) : base(descriptor) { + m_value = (float)ToastSettings.GetFloat(descriptor.Key); + } + + public double Minimum => Descriptor.HasRange ? Descriptor.Min : double.NegativeInfinity; + + public double Maximum => Descriptor.HasRange ? Descriptor.Max : double.PositiveInfinity; + + partial void OnValueChanged(float value) { + if (SuppressWrite) return; + ToastSettings.SetFloat(Key, value); + Written(); + } + + protected override void ReadValue() => Value = (float)ToastSettings.GetFloat(Key); +} + +public sealed partial class ChoiceSettingRow : SettingRow { + [ObservableProperty] private int m_selectedIndex; + + public ChoiceSettingRow(SettingDescriptor descriptor) : base(descriptor) { + Options = new ObservableCollection(descriptor.Options); + m_selectedIndex = Clamp((int)ToastSettings.GetInt(descriptor.Key)); + } + + public ObservableCollection Options { get; } + + public string? SelectedName { + get => SelectedIndex >= 0 && SelectedIndex < Options.Count ? Options[SelectedIndex] : null; + set { + var index = value is null ? -1 : Options.IndexOf(value); + if (index >= 0) SelectedIndex = index; + } + } + + partial void OnSelectedIndexChanged(int value) { + OnPropertyChanged(nameof(SelectedName)); + if (value < 0 || SuppressWrite) return; + ToastSettings.SetInt(Key, value); + Written(); + } + + protected override void ReadValue() => SelectedIndex = Clamp((int)ToastSettings.GetInt(Key)); + + private int Clamp(int index) => Options.Count == 0 ? -1 : Math.Clamp(index, 0, Options.Count - 1); +} + +public sealed partial class TextSettingRow : SettingRow { + [ObservableProperty] private string m_value; + + public TextSettingRow(SettingDescriptor descriptor) : base(descriptor) { + m_value = ToastSettings.GetString(descriptor.Key); + } + + partial void OnValueChanged(string value) { + if (SuppressWrite) return; + ToastSettings.SetString(Key, value ?? string.Empty); + Written(); + } + + protected override void ReadValue() => Value = ToastSettings.GetString(Key); +} + +public sealed partial class AssetSettingRow : SettingRow { + [ObservableProperty] private string m_value; + + public AssetSettingRow(SettingDescriptor descriptor) : base(descriptor) { + m_value = ToastSettings.GetString(descriptor.Key); + } + + public string AssetType => Descriptor.AssetType; + + partial void OnValueChanged(string value) { + if (SuppressWrite) return; + ToastSettings.SetString(Key, value ?? string.Empty); + Written(); + } + + protected override void ReadValue() => Value = ToastSettings.GetString(Key); +} + +public sealed partial class VectorSettingRow : SettingRow { + private readonly int m_components; + + [ObservableProperty] private float m_w; + [ObservableProperty] private float m_x; + [ObservableProperty] private float m_y; + [ObservableProperty] private float m_z; + + public VectorSettingRow(SettingDescriptor descriptor, int components) : base(descriptor) { + m_components = components; + Parse(ToastSettings.GetText(descriptor.Key)); + } + + public bool IsVec2 => m_components == 2; + public bool IsVec3 => m_components == 3; + public bool IsVec4 => m_components == 4; + + public double Minimum => Descriptor.HasRange ? Descriptor.Min : double.NegativeInfinity; + public double Maximum => Descriptor.HasRange ? Descriptor.Max : double.PositiveInfinity; + + partial void OnXChanged(float value) => Write(); + partial void OnYChanged(float value) => Write(); + partial void OnZChanged(float value) => Write(); + partial void OnWChanged(float value) => Write(); + + private void Write() { + if (SuppressWrite) return; + var parts = new[] { X, Y, Z, W }.Take(m_components).Select(v => v.ToString("R", CultureInfo.InvariantCulture)); + if (ToastSettings.SetText(Key, string.Join(' ', parts), out var error)) { + Error = string.Empty; + Written(); + } else Error = error; + } + + protected override void ReadValue() => Parse(ToastSettings.GetText(Key)); + + private void Parse(string text) { + var numbers = text.Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Select(p => float.TryParse(p, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : 0f) + .ToArray(); + + float At(int i) => i < numbers.Length ? numbers[i] : 0f; + + var previous = SuppressWrite; + SuppressWrite = true; + X = At(0); + Y = At(1); + Z = At(2); + W = At(3); + SuppressWrite = previous; + } +} + +public sealed partial class ArrayItem : ObservableObject { + [ObservableProperty] private string m_text; + + public ArrayItem(string text) { + m_text = text; + } +} + +public sealed partial class ArraySettingRow : SettingRow { + private string? m_lastText; + + public ArraySettingRow(SettingDescriptor descriptor) : base(descriptor) { + Items.CollectionChanged += OnItemsChanged; + Fill(ToastSettings.GetText(descriptor.Key)); + } + + public ObservableCollection Items { get; } = []; + + private bool IsStrings => Descriptor.ValueType == SettingType.String; + + private string NewElement => Descriptor.ValueType switch { + SettingType.Bool => "false", + SettingType.String => string.Empty, + SettingType.Vec2 => "0 0", + SettingType.Vec3 => "0 0 0", + SettingType.Vec4 => "0 0 0 0", + SettingType.Quat => "0 0 0 1", + SettingType.Asset => string.Empty, + _ => "0" + }; + + [RelayCommand] + private void Add() { + Items.Add(new ArrayItem(NewElement)); + } + + private void OnItemsChanged(object? sender, NotifyCollectionChangedEventArgs e) { + if (e.OldItems is not null) + foreach (ArrayItem item in e.OldItems) item.PropertyChanged -= OnItemChanged; + if (e.NewItems is not null) + foreach (ArrayItem item in e.NewItems) item.PropertyChanged += OnItemChanged; + Commit(); + } + + private void OnItemChanged(object? sender, PropertyChangedEventArgs e) { + Commit(); + } + + private void Commit() { + if (SuppressWrite || m_filling) return; + var text = string.Join(';', Items.Select(i => Encode(i.Text))); + if (ToastSettings.SetText(Key, text, out var error)) { + m_lastText = ToastSettings.GetText(Key); + Error = string.Empty; + Written(); + } else Error = error; + } + + protected override void ReadValue() => Fill(ToastSettings.GetText(Key)); + + private bool m_filling; + + private void Fill(string text) { + if (text == m_lastText) return; + m_lastText = text; + + m_filling = true; + try { + Items.Clear(); + foreach (var element in SplitElements(text)) Items.Add(new ArrayItem(Decode(element))); + } finally { + m_filling = false; + } + } + + private string Decode(string element) { + if (!IsStrings || element.Length < 2 || element[0] != '"' || element[^1] != '"') return element; + return element[1..^1].Replace("\\\"", "\"").Replace("\\\\", "\\"); + } + + private string Encode(string shown) { + return IsStrings ? "\"" + shown.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"" : shown; + } + + public static List SplitElements(string text) { + var parts = new List(); + if (string.IsNullOrWhiteSpace(text)) return parts; + + var start = 0; + var quoted = false; + for (var i = 0; i < text.Length; i++) { + if (text[i] == '\\' && quoted) i++; + else if (text[i] == '"') quoted = !quoted; + else if (text[i] == ';' && !quoted) { + parts.Add(text[start..i].Trim()); + start = i + 1; + } + } + + parts.Add(text[start..].Trim()); + return parts; + } +} diff --git a/editor/Settings/SettingsPanelState.cs b/editor/Settings/SettingsPanelState.cs new file mode 100644 index 000000000..eff51e3a7 --- /dev/null +++ b/editor/Settings/SettingsPanelState.cs @@ -0,0 +1,74 @@ +// +// SettingsPanelState.cs by Xein +// 24 Nov 2026 +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using editor.Assets; + +namespace editor.Settings; + +public sealed class SettingsPanelState { + private static SettingsPanelState? s_current; + private static string s_currentPath = string.Empty; + + private string m_path = string.Empty; + + public double WindowWidth { get; set; } = 860; + public double WindowHeight { get; set; } = 700; + public double NavWidth { get; set; } = 190; + + public Dictionary Toggles { get; set; } = []; + + public static SettingsPanelState Current { + get { + var path = ProjectContext.IsInitialized ? ProjectContext.Resolve("cache://tools/settings_panel.json") : string.Empty; + if (s_current is not null && s_currentPath == path) return s_current; + s_currentPath = path; + s_current = Load(path); + return s_current; + } + } + + private static SettingsPanelState Load(string path) { + try { + if (path.Length > 0 && File.Exists(path)) { + var loaded = JsonSerializer.Deserialize(File.ReadAllText(path)); + if (loaded is not null) { + loaded.m_path = path; + loaded.Toggles ??= []; + loaded.WindowWidth = Math.Clamp(loaded.WindowWidth, 600, 4000); + loaded.WindowHeight = Math.Clamp(loaded.WindowHeight, 400, 4000); + loaded.NavWidth = Math.Clamp(loaded.NavWidth, 120, 500); + return loaded; + } + } + } catch { + } + + return new SettingsPanelState { m_path = path }; + } + + public bool Get(string key, bool fallback) => Toggles.TryGetValue(key, out var value) ? value : fallback; + + public void Set(string key, bool value, bool fallback) { + if (value == fallback) Toggles.Remove(key); + else Toggles[key] = value; + Save(); + } + + public void Save() { + if (m_path.Length == 0) return; + try { + Directory.CreateDirectory(Path.GetDirectoryName(m_path)!); + var temp = m_path + ".tmp." + Guid.NewGuid().ToString("N"); + File.WriteAllText(temp, JsonSerializer.Serialize(this)); + File.Move(temp, m_path, true); + } catch { + // best effort, like the other editor state + } + } +} diff --git a/editor/Settings/SettingsTree.cs b/editor/Settings/SettingsTree.cs new file mode 100644 index 000000000..93a1f12f6 --- /dev/null +++ b/editor/Settings/SettingsTree.cs @@ -0,0 +1,161 @@ +// +// SettingsTree.cs by Xein +// 24 Nov 2026 +// + +using System; +using System.Collections.Generic; +using System.Linq; +using editor.Engine; + +namespace editor.Settings; + +public sealed class SettingsCard { + public required string Key { get; init; } + public required string Title { get; init; } + + public List Normal { get; } = []; + + public List Advanced { get; } = []; + public List Debug { get; } = []; + + public IEnumerable All => Normal.Concat(Advanced).Concat(Debug); +} + +public sealed class SettingsPageModel { + public required string Key { get; init; } + public required string Title { get; init; } + public List Cards { get; } = []; +} + +public static class SettingsTree { + public const string EditorPage = "editor"; + public const string ProjectPage = "project"; + public const string GamePage = "game"; + + private static readonly HashSet s_custom = ["physics.layers.names", "physics.layers.abbreviations"]; + + private static readonly Dictionary s_pageOfGroup = new() { + ["project"] = ProjectPage, + ["gameplay"] = GamePage, + ["ui"] = "ui" + }; + + private static readonly Dictionary s_pageOfKey = new() { + ["project.max_tick_rate"] = GamePage + }; + + private static readonly Dictionary s_pageTitles = new() { + [ProjectPage] = "Project", + [GamePage] = "Game", + ["ui"] = "UI", + ["renderer"] = "Rendering", + [EditorPage] = "Editor" + }; + + private static readonly HashSet s_acronyms = new(StringComparer.OrdinalIgnoreCase) { + "gi", "ui", "hdr", "ssr", "ssao", "taa", "fxaa", "rt", "ao", "lod", "fov", "ik", "hud", "vfx", "sdf", "pbr" + }; + + public static bool IsCustom(string key) => s_custom.Contains(key); + + public static string GroupOf(string key) { + var dot = key.IndexOf('.'); + return dot < 0 ? key : key[..dot]; + } + + public static string IdOf(string key) { + var dot = key.IndexOf('.'); + return dot < 0 ? key : key[(dot + 1)..]; + } + + public static string Pretty(string segment) { + if (segment.Length == 0) return segment; + if (s_acronyms.Contains(segment)) return segment.ToUpperInvariant(); + var spaced = segment.Replace('_', ' '); + return char.ToUpperInvariant(spaced[0]) + spaced[1..]; + } + + public static string PrettyPath(string path) => string.Join(" / ", path.Split('.', StringSplitOptions.RemoveEmptyEntries).Select(Pretty)); + + public static string LabelOf(SettingDescriptor descriptor) { + var id = IdOf(descriptor.Key); + if (descriptor.Label.Length > 0 && descriptor.Label != id) return descriptor.Label; + var dot = id.LastIndexOf('.'); + return Pretty(dot < 0 ? id : id[(dot + 1)..]); + } + + public static string PageOf(string group) => s_pageOfGroup.TryGetValue(group, out var page) ? page : group; + + public static string PageOfKey(string key) => s_pageOfKey.TryGetValue(key, out var page) ? page : PageOf(GroupOf(key)); + + public static string TitleOfPage(string page) => s_pageTitles.TryGetValue(page, out var title) ? title : Pretty(page); + + public static List Build(IEnumerable descriptors) { + var all = descriptors.Where(d => !IsCustom(d.Key)).ToList(); + var pages = new List(); + + SettingsPageModel PageFor(string key) { + var existing = pages.FirstOrDefault(p => p.Key == key); + if (existing is not null) return existing; + var created = new SettingsPageModel { Key = key, Title = TitleOfPage(key) }; + pages.Add(created); + return created; + } + + var groupsPerPage = all + .Where(d => d.Kind != SettingKind.User) + .Select(d => (Group: GroupOf(d.Key), Page: PageOfKey(d.Key))) + .Distinct() + .GroupBy(d => d.Page) + .ToDictionary(g => g.Key, g => g.Count()); + + foreach (var descriptor in all) { + var group = GroupOf(descriptor.Key); + var id = IdOf(descriptor.Key); + var subgroup = id.Contains('.') ? id[..id.LastIndexOf('.')] : string.Empty; + + var isPreference = descriptor.Kind == SettingKind.User; + var page = PageFor(isPreference ? EditorPage : PageOfKey(descriptor.Key)); + var shared = groupsPerPage.GetValueOrDefault(page.Key) > 1 || (isPreference && group != "editor"); + + var cardKey = $"{group}/{subgroup}"; + var title = subgroup.Length == 0 + ? shared ? Pretty(group) : "General" + : shared ? $"{Pretty(group)} / {PrettyPath(subgroup)}" : PrettyPath(subgroup); + + if (s_pageOfKey.ContainsKey(descriptor.Key)) title = "Timing"; + + var card = page.Cards.FirstOrDefault(c => c.Key == cardKey); + if (card is null) { + card = new SettingsCard { Key = cardKey, Title = title }; + page.Cards.Add(card); + } + + switch (descriptor.Kind) { + case SettingKind.Advanced: card.Advanced.Add(descriptor); break; + case SettingKind.Debug: card.Debug.Add(descriptor); break; + default: card.Normal.Add(descriptor); break; + } + } + + foreach (var card in pages.SelectMany(p => p.Cards)) { + if (card.Normal.Count > 0) continue; + if (card.Advanced.Count > 0) { + card.Normal.AddRange(card.Advanced); + card.Advanced.Clear(); + } else { + card.Normal.AddRange(card.Debug); + card.Debug.Clear(); + } + } + + var editor = pages.FirstOrDefault(p => p.Key == EditorPage); + if (editor is not null) { + pages.Remove(editor); + pages.Add(editor); + } + + return pages; + } +} diff --git a/editor/Workspace/AssetBrowserSettingsView.axaml b/editor/Workspace/AssetBrowserSettingsView.axaml new file mode 100644 index 000000000..8c4f8c3c1 --- /dev/null +++ b/editor/Workspace/AssetBrowserSettingsView.axaml @@ -0,0 +1,336 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/editor/Workspace/AssetBrowserSettingsView.axaml.cs b/editor/Workspace/AssetBrowserSettingsView.axaml.cs new file mode 100644 index 000000000..8b69d5645 --- /dev/null +++ b/editor/Workspace/AssetBrowserSettingsView.axaml.cs @@ -0,0 +1,19 @@ +// +// AssetBrowserSettingsView.cs by Xein +// 24 Nov 2026 +// + +using Avalonia.Controls; +using Avalonia.Markup.Xaml; + +namespace editor.Workspace; + +public partial class AssetBrowserSettingsView : UserControl { + public AssetBrowserSettingsView() { + InitializeComponent(); + } + + private void InitializeComponent() { + AvaloniaXamlLoader.Load(this); + } +} diff --git a/editor/Workspace/AssetBrowserSettingsViewModel.cs b/editor/Workspace/AssetBrowserSettingsViewModel.cs index b6f25fa34..acd1ba5a3 100644 --- a/editor/Workspace/AssetBrowserSettingsViewModel.cs +++ b/editor/Workspace/AssetBrowserSettingsViewModel.cs @@ -36,6 +36,32 @@ public AssetBrowserSettingsViewModel() { public string[] SortOptions { get; } = Enum.GetNames(); public string[] SearchScopes { get; } = ["Everywhere", "Current folder"]; + public string CardSizeName { + get => CardSizes[Math.Clamp(CardSizeIndex, 0, CardSizes.Length - 1)]; + set { var i = Array.IndexOf(CardSizes, value); if (i >= 0) CardSizeIndex = i; } + } + + public string SortByName { + get => SortOptions[Math.Clamp(SortByIndex, 0, SortOptions.Length - 1)]; + set { var i = Array.IndexOf(SortOptions, value); if (i >= 0) SortByIndex = i; } + } + + public string SearchScopeName { + get => SearchScopes[Math.Clamp(SearchScopeIndex, 0, SearchScopes.Length - 1)]; + set { var i = Array.IndexOf(SearchScopes, value); if (i >= 0) SearchScopeIndex = i; } + } + + public bool TagsExpanded { get => Fold("tags"); set => SetFold("tags", value, nameof(TagsExpanded)); } + public bool DisplayExpanded { get => Fold("display"); set => SetFold("display", value, nameof(DisplayExpanded)); } + public bool BehaviourExpanded { get => Fold("behaviour"); set => SetFold("behaviour", value, nameof(BehaviourExpanded)); } + + private static bool Fold(string name) => editor.Settings.SettingsPanelState.Current.Get("card:assetbrowser/" + name, true); + + private void SetFold(string name, bool value, string property) { + editor.Settings.SettingsPanelState.Current.Set("card:assetbrowser/" + name, value, true); + OnPropertyChanged(property); + } + public bool ShowTags { get => AssetBrowserSettings.ShowTags; set => AssetBrowserSettings.SetShowTags(value); diff --git a/editor/Workspace/AutosaveService.cs b/editor/Workspace/AutosaveService.cs index eff5fdeb4..a24331fa6 100644 --- a/editor/Workspace/AutosaveService.cs +++ b/editor/Workspace/AutosaveService.cs @@ -24,7 +24,8 @@ public interface IAutosavable { // Writes every dirty open editor to cache://autosaves/ once a minute public sealed class AutosaveService { private const string AutosaveDir = "cache://autosaves/"; - private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1); + private const string EnabledKey = "editor.autosave.enabled"; + private const string IntervalKey = "editor.autosave.interval_seconds"; private readonly Func> m_sources; private readonly DispatcherTimer m_timer; @@ -32,11 +33,18 @@ public sealed class AutosaveService { public AutosaveService(Func> sources) { m_sources = sources; - m_timer = new DispatcherTimer { Interval = Interval }; - m_timer.Tick += async (_, _) => await RequestAutosave(); + m_timer = new DispatcherTimer { Interval = CurrentInterval() }; + m_timer.Tick += async (_, _) => { + m_timer.Interval = CurrentInterval(); + if (ToastSettings.Flag(EnabledKey, true)) await RequestAutosave(); + }; m_timer.Start(); } + private static TimeSpan CurrentInterval() { + return TimeSpan.FromSeconds(Math.Clamp(ToastSettings.Number(IntervalKey, 60), 10, 3600)); + } + public void Stop() { m_timer.Stop(); } diff --git a/editor/Workspace/MainWindowViewModel.cs b/editor/Workspace/MainWindowViewModel.cs index 259ef9336..6b0a9b656 100644 --- a/editor/Workspace/MainWindowViewModel.cs +++ b/editor/Workspace/MainWindowViewModel.cs @@ -1160,11 +1160,9 @@ private async Task SaveBeforeBuild(Avalonia.Controls.Window owner) { return true; } - /// Engine and game in RelWithDebInfo: optimized, with the dev tools, Tracy and full symbols [RelayCommand(CanExecute = nameof(CanCompileGameRelease))] private Task CompileGameDevelopment() => CompileGame("RelWithDebInfo"); - /// Engine and game in Release: full optimization, no dev tools or Tracy [RelayCommand(CanExecute = nameof(CanCompileGameRelease))] private Task CompileGameRelease() => CompileGame("Release"); @@ -1172,7 +1170,6 @@ private async Task CompileGame(string gameConfig) { if (App.MainWindow is not { } owner) return; if (!ProjectContext.IsInitialized) return; - // The game links against the engine of the same config, which sits next to the editor's own out// var toastPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", gameConfig, "toast_engine")); if (!File.Exists(Path.Combine(toastPath, "bin", OperatingSystem.IsWindows() ? "toast_engine.dll" : "libtoast_engine.so"))) { Log.Error($"Cannot build the game in {gameConfig}: the {gameConfig} engine was not built ({toastPath})"); @@ -1240,7 +1237,33 @@ async Task CopyProjectToast(Action log) { await Task.Run(() => File.Copy(toastFile, dest, true)); } - // The engine's crash handler looks for crash_reporter/ next to toast_engine.dll; runtimes/ holds its native libraries + async Task CookConfigs(Action log) { + var configDir = Path.Combine(ProjectContext.ProjectPath, "config"); + var toastFile = Directory.EnumerateFiles(ProjectContext.ProjectPath, "*.toast").FirstOrDefault() ?? ""; + var stageDir = Path.Combine(stageRoot, "configs"); + if (Directory.Exists(stageDir)) Directory.Delete(stageDir, true); + + log(" cooking config://"); + if (!await Task.Run(() => ToastSettings.Cook(configDir, toastFile, stageDir))) + throw new Exception("could not cook the config files; the log says which one"); + + var pakOut = Path.Combine(outputDir, "configs.pak"); + log(" packing → configs.pak"); + await Task.Run(() => { + using var proc = new Process(); + proc.StartInfo = new ProcessStartInfo { + FileName = packerBin, + Arguments = $"\"{stageDir}\" \"{pakOut}\"", + WorkingDirectory = ProjectContext.ProjectPath, + UseShellExecute = false, + CreateNoWindow = true + }; + var exitCode = TerminalReader.Run(proc, log); + if (exitCode != 0) + throw new Exception($"packer exited with code {exitCode} for configs"); + }); + } + async Task CopyCrashReporter(Action log) { var src = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "crash_reporter")); if (!Directory.Exists(src)) { @@ -1351,6 +1374,7 @@ await Task.Run(() => { LoaderTask.Do("copy libraries", CopyDlls), LoaderTask.Do("copy crash reporter", CopyCrashReporter), LoaderTask.Do("copy project.toast", CopyProjectToast), + LoaderTask.Do("cook configs", CookConfigs), LoaderTask.Do("copy baked lighting", CopyBakedLighting) }; diff --git a/editor/Workspace/PlayModeShortcuts.cs b/editor/Workspace/PlayModeShortcuts.cs index 789c2c736..51c33ca9f 100644 --- a/editor/Workspace/PlayModeShortcuts.cs +++ b/editor/Workspace/PlayModeShortcuts.cs @@ -4,12 +4,13 @@ using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; +using editor.Engine; namespace editor.Workspace; // the game owns the keyboard while any workspace plays so no editor shortcut may fire internal static class PlayModeShortcuts { - public static bool Blocked => WorkspaceViewModel.AnyPlayActive && ViewportControl.AnyGameInput; + public static bool Blocked => ToastEngine.ConsoleOpen || (WorkspaceViewModel.AnyPlayActive && ViewportControl.AnyGameInput); // KeyBindings fire before any routed handler and only check CanExecute so their commands get wrapped // app wide instead of disabled which would also grey out the menus diff --git a/editor/Workspace/ProjectSettingsView.axaml b/editor/Workspace/ProjectSettingsView.axaml index 7606d2beb..09d2de1f3 100644 --- a/editor/Workspace/ProjectSettingsView.axaml +++ b/editor/Workspace/ProjectSettingsView.axaml @@ -1,15 +1,15 @@ @@ -21,7 +21,7 @@ - - + + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + - - + + - - + + Maximum="{Binding Maximum}" + Unit="{Binding Unit}" + Classes="compact-field" /> - - + + + + + + - + + AssetType="{Binding AssetType}" + Classes="compact-field" /> - - + + + + + + + + + + + + + + + + - - - - - - - - + Classes="card"> + + + + + + + + + + + + + + + + + + + - + Classes="card"> - - - - + + + + - - - - - - - + Margin="0,0,0,8" + IsVisible="{Binding ShowBaking}"> + Classes="group compact-text" /> - - - - - - - - - - - - - + + + - + + + + IsVisible="{Binding ShowPhysicsLayers}"> - - - + + @@ -279,7 +553,7 @@ Margin="0,0,0,4"> + Background="{StaticResource Bg1}" + Classes="compact-control" /> + Background="{StaticResource Bg1}" + Classes="compact-control" /> @@ -309,262 +585,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/editor/Workspace/ProjectSettingsView.axaml.cs b/editor/Workspace/ProjectSettingsView.axaml.cs index 92f4100f0..a9441f916 100644 --- a/editor/Workspace/ProjectSettingsView.axaml.cs +++ b/editor/Workspace/ProjectSettingsView.axaml.cs @@ -4,7 +4,9 @@ // using Avalonia.Controls; +using Avalonia.Input; using Avalonia.Markup.Xaml; +using editor.Settings; namespace editor.Workspace; @@ -12,10 +14,31 @@ public partial class ProjectSettingsView : UserControl { public ProjectSettingsView() { InitializeComponent(); - AttachedToVisualTree += (_, _) => (DataContext as ProjectSettingsViewModel)?.StartPolling(); + var columns = this.FindControl("Columns")!; + var splitter = this.FindControl("NavSplitter")!; + + AttachedToVisualTree += (_, _) => { + columns.ColumnDefinitions[0].Width = new GridLength(SettingsPanelState.Current.NavWidth); + (DataContext as ProjectSettingsViewModel)?.StartPolling(); + }; + splitter.DragCompleted += (_, _) => { + SettingsPanelState.Current.NavWidth = columns.ColumnDefinitions[0].ActualWidth; + SettingsPanelState.Current.Save(); + }; DetachedFromVisualTree += (_, _) => (DataContext as ProjectSettingsViewModel)?.StopPolling(); } + private void OnNavPressed(object? sender, PointerPressedEventArgs e) { + if (sender is Control { DataContext: SettingsNavItem item } && DataContext is ProjectSettingsViewModel vm) vm.SelectNav(item); + } + + private void OnNavChevronPressed(object? sender, PointerPressedEventArgs e) { + if (sender is Control { DataContext: SettingsNavItem item } && DataContext is ProjectSettingsViewModel vm && item.HasChildren) { + vm.ToggleNav(item); + e.Handled = true; + } + } + private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } diff --git a/editor/Workspace/ProjectSettingsViewModel.cs b/editor/Workspace/ProjectSettingsViewModel.cs index 145164bdd..c832faf43 100644 --- a/editor/Workspace/ProjectSettingsViewModel.cs +++ b/editor/Workspace/ProjectSettingsViewModel.cs @@ -1,6 +1,6 @@ // // ProjectSettingsViewModel.cs -// 22 Sep 2026 +// 22 Sep 2026, rewritten 24 Nov 2026 // using System; @@ -8,14 +8,15 @@ using System.Collections.ObjectModel; using System.IO; using System.Linq; +using Avalonia; using Avalonia.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Dock.Model.Mvvm.Controls; using editor.Assets; using editor.Assets.Types; -using editor.Editors; using editor.Engine; +using editor.Settings; namespace editor.Workspace; @@ -23,31 +24,155 @@ public enum SettingsTab { General, Rendering, Physics, - Editor + Editor, + + Group +} + +public enum SettingsExtra { + None, + General, + PhysicsLayers, + Baking, + AssetBrowser } public sealed class SettingsSection { public required string Name { get; init; } public required SettingsTab Tab { get; init; } + public string? PageKey { get; init; } + + public string? CardKey { get; init; } + public string? Category { get; init; } + public SettingsExtra Extra { get; init; } public ObservableCollection Children { get; } = []; +} + +public sealed partial class SettingsNavItem : ObservableObject { + [ObservableProperty] private bool m_isExpanded = true; + [ObservableProperty] private bool m_isSelected; + + public SettingsNavItem(SettingsSection section, int depth) { + Section = section; + Depth = depth; + } + + public SettingsSection Section { get; } + public int Depth { get; } + public string Name => Section.Name; + public bool HasChildren => Section.Children.Count > 0; + public Thickness Indent => new(10 + (Depth * 20), 0, 0, 0); +} + +public sealed partial class SettingsCardViewModel : ObservableObject { + private readonly List m_normal; + private readonly List m_advanced; + private readonly List m_debug; + + private static readonly string[] s_accents = ["Red", "Orange", "Yellow", "Green", "Cyan", "Blue", "Magenta"]; + + private readonly string m_stateKey; + private bool m_restoring; + private bool m_searching; + + public SettingsCardViewModel(SettingsCard card, string pageKey, int index, ProjectInfoViewModel? info = null) { + Key = card.Key; + Title = info is not null ? "Project" : card.Title; + Info = info; + ColorKey = s_accents[index % s_accents.Length]; + m_stateKey = pageKey + "/" + card.Key; + m_normal = card.Normal.Select(SettingRow.Create).ToList(); + m_advanced = card.Advanced.Select(SettingRow.Create).ToList(); + m_debug = card.Debug.Select(SettingRow.Create).ToList(); + + // how it was left the last time + m_restoring = true; + var state = SettingsPanelState.Current; + Expanded = state.Get("card:" + m_stateKey, true); + AdvancedExpanded = state.Get("advanced:" + m_stateKey, false); + DebugExpanded = state.Get("debug:" + m_stateKey, true); + m_restoring = false; + } + + [ObservableProperty] private bool m_advancedExpanded; + [ObservableProperty] private bool m_debugExpanded = true; + [ObservableProperty] private bool m_expanded = true; + + public string Key { get; } + public string Title { get; } + public string ColorKey { get; } + + public ProjectInfoViewModel? Info { get; } + public bool HasInfo => Info is not null; + + partial void OnExpandedChanged(bool value) { + if (!m_restoring) SettingsPanelState.Current.Set("card:" + m_stateKey, value, true); + } - public bool IsRoot => Category is null; + partial void OnAdvancedExpandedChanged(bool value) { + if (!m_restoring && !m_searching) SettingsPanelState.Current.Set("advanced:" + m_stateKey, value, false); + } + + partial void OnDebugExpandedChanged(bool value) { + if (!m_restoring && !m_searching) SettingsPanelState.Current.Set("debug:" + m_stateKey, value, true); + } + + public ObservableCollection Normal { get; } = []; + public ObservableCollection Advanced { get; } = []; + public ObservableCollection Debug { get; } = []; + + public bool HasAdvanced => Advanced.Count > 0; + public bool HasDebug => Debug.Count > 0; + public bool IsVisible => Normal.Count + Advanced.Count + Debug.Count > 0 || (Info is not null && !m_searching); + + public IEnumerable AllRows => m_normal.Concat(m_advanced).Concat(m_debug); + + public void ApplyFilter(string query, bool showAdvanced, bool showDebug) { + var searching = query.Length > 0; + Fill(Normal, m_normal, query, true); + Fill(Advanced, m_advanced, query, showAdvanced || searching); + Fill(Debug, m_debug, query, showDebug || searching); + + m_searching = searching; + if (searching) { + if (Advanced.Count > 0) AdvancedExpanded = true; + if (Debug.Count > 0) DebugExpanded = true; + } + + OnPropertyChanged(nameof(HasAdvanced)); + OnPropertyChanged(nameof(HasDebug)); + OnPropertyChanged(nameof(IsVisible)); + } + + private static void Fill(ObservableCollection target, List source, string query, bool show) { + var wanted = show ? source.Where(r => query.Length == 0 || r.Matches(query)).ToList() : []; + if (target.SequenceEqual(wanted)) return; + target.Clear(); + foreach (var row in wanted) target.Add(row); + } } public partial class ProjectSettingsViewModel : Tool { - private const string RendererPrefix = "renderer."; - private const string PhysicsPrefix = "physics."; public const string AssetBrowserCategory = "Asset Browser"; - public const string PhysicsTagsCategory = "Tags"; + public const string PhysicsLayersCategory = "Layers"; + public const string BakingCategory = "Baking"; + + private static readonly HashSet s_flatPages = ["project", "game", "assets"]; + + private const string ProjectPage = "project"; + private const string PhysicsPage = "physics"; + private const string RendererPage = "renderer"; - private readonly DispatcherTimer m_statusTimer; + private readonly DispatcherTimer m_refreshTimer; + private List m_pages = []; [ObservableProperty] private uint m_irradianceProbeCount; [ObservableProperty] private bool m_rayTracingSupported; [ObservableProperty] private string m_savePath = string.Empty; + [ObservableProperty] private string m_searchText = string.Empty; [ObservableProperty] private SettingsSection? m_selectedSection; [ObservableProperty] private uint m_staleIrradianceVolumes; [ObservableProperty] private uint m_staleReflectionProbes; @@ -55,18 +180,21 @@ public partial class ProjectSettingsViewModel : Tool { public ProjectSettingsViewModel() { Sections = []; - VisibleCategories = []; - GeneralEditor = new GenericViewModel { Id = "ProjectSettingsGeneral", Title = "General" }; + Cards = []; - m_statusTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1.0) }; - m_statusTimer.Tick += (_, _) => RefreshStatus(); + m_refreshTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1.0) }; + m_refreshTimer.Tick += (_, _) => RefreshLive(); AssetBrowserSettings.Saved += ok => { - if (IsEditor) StatusMessage = ok ? $"Saved to {Path.GetFileName(SavePathOfProject())}" : "Save failed"; + if (IsAssetBrowser) StatusMessage = ok ? $"Saved to {Path.GetFileName(SavePathOfProject())}" : "Save failed"; }; } - public GenericViewModel GeneralEditor { get; } + public ProjectInfoViewModel ProjectInfo { get; } = new(); + + public ObservableCollection NavRows { get; } = []; + + private readonly Dictionary m_navItems = []; public AssetBrowserSettingsViewModel AssetBrowser { get; } = new(); @@ -74,17 +202,28 @@ public ProjectSettingsViewModel() { public ObservableCollection Sections { get; } - public ObservableCollection VisibleCategories { get; } + public ObservableCollection Cards { get; } + + public SettingsExtra ActiveExtra => SelectedSection?.Extra ?? SettingsExtra.None; + public bool IsPhysicsLayers => ActiveExtra == SettingsExtra.PhysicsLayers; + + public bool ShowPhysicsLayers => IsPhysicsLayers || SelectedSection is { Extra: SettingsExtra.None, PageKey: PhysicsPage, CardKey: null }; + public bool IsAssetBrowser => ActiveExtra == SettingsExtra.AssetBrowser; - public SettingsTab ActiveTab => SelectedSection?.Tab ?? SettingsTab.General; + public bool ShowAssetBrowser => IsAssetBrowser || SelectedSection is { Extra: SettingsExtra.None, PageKey: SettingsTree.EditorPage, CardKey: null }; - public bool IsGeneral => ActiveTab == SettingsTab.General; - public bool IsRendering => ActiveTab == SettingsTab.Rendering; - public bool IsPhysics => ActiveTab == SettingsTab.Physics; - public bool IsPhysicsTags => IsPhysics && SelectedSection?.Category == PhysicsTagsCategory; - public bool IsEditor => ActiveTab == SettingsTab.Editor; - public bool IsEngineTab => IsRendering || IsPhysics; - public bool IsSettingList => IsEngineTab && !IsPhysicsTags; + public bool ShowBaking => ActiveExtra == SettingsExtra.Baking || (SelectedSection is { Extra: SettingsExtra.None, PageKey: RendererPage, CardKey: null }); + + public bool ShowCards => ActiveExtra is SettingsExtra.None; + + public bool IsSearching => SearchText.Length > 0; + public bool NothingToShow => ShowCards && Cards.Count == 0; + + public string EmptyMessage => IsSearching + ? "Nothing matches that." + : "Nothing declared here yet. A system declares its parameters when it starts, so open a workspace."; + + public string SectionTitle => SelectedSection is null ? string.Empty : SelectedSection.CardKey is null ? SelectedSection.Name : $"{PageName(SelectedSection)} / {SelectedSection.Name}"; public bool HasStaleReflectionProbes => StaleReflectionProbes > 0; public bool HasStaleIrradianceVolumes => StaleIrradianceVolumes > 0; @@ -92,56 +231,106 @@ public ProjectSettingsViewModel() { public void Load() { var previous = SelectedSection; + m_pages = SettingsTree.Build(ToastSettings.Enumerate()); + Sections.Clear(); - Sections.Add(BuildRoot("General", SettingsTab.General, [])); - Sections.Add(BuildRoot("Rendering", SettingsTab.Rendering, SettingRowFactory.BuildCategories(RendererPrefix))); - var physics = BuildRoot("Physics", SettingsTab.Physics, SettingRowFactory.BuildCategories(PhysicsPrefix)); - physics.Children.Add(new SettingsSection - { Name = PhysicsTagsCategory, Tab = SettingsTab.Physics, Category = PhysicsTagsCategory }); - Sections.Add(physics); - Sections.Add(BuildEditorRoot()); + + foreach (var page in m_pages.Where(p => p.Key != SettingsTree.EditorPage)) Sections.Add(BuildRoot(page)); + Sections.Add(BuildEditorRoot(m_pages.FirstOrDefault(p => p.Key == SettingsTree.EditorPage))); PhysicsLayers.Reload(); SavePath = ToastSettings.ActivePath; RayTracingSupported = ToastRenderer.SupportsRayTracing; RefreshStatus(); + ProjectInfo.Load(); - OpenProjectSettingsFile(); - - SelectedSection = Sections - .SelectMany(root => new[] { root }.Concat(root.Children)) - .FirstOrDefault(s => s.Tab == previous?.Tab && s.Category == previous?.Category) - ?? Sections[0]; + SelectedSection = Flatten().FirstOrDefault(s => previous is not null && Same(s, previous)) ?? Sections[0]; + RebuildNav(); + RebuildCards(); } public void StartPolling() { if (Sections.Count == 0) Load(); - m_statusTimer.Start(); + m_refreshTimer.Start(); } public void StopPolling() { - m_statusTimer.Stop(); + m_refreshTimer.Stop(); } public void SelectSection(SettingsTab tab, string? category = null) { if (Sections.Count == 0) Load(); - SelectedSection = Sections - .SelectMany(root => new[] { root }.Concat(root.Children)) - .FirstOrDefault(s => s.Tab == tab && s.Category == category) - ?? SelectedSection; + SelectedSection = Flatten().FirstOrDefault(s => s.Tab == tab && s.Category == category) ?? SelectedSection; + } + + private IEnumerable Flatten() => Sections.SelectMany(root => new[] { root }.Concat(root.Children)); + + private static bool Same(SettingsSection a, SettingsSection b) { + return a.Tab == b.Tab && a.PageKey == b.PageKey && a.CardKey == b.CardKey && a.Extra == b.Extra && a.Category == b.Category; } - private static SettingsSection BuildEditorRoot() { - var root = new SettingsSection { Name = "Editor", Tab = SettingsTab.Editor }; - root.Children.Add(new SettingsSection - { Name = AssetBrowserCategory, Tab = SettingsTab.Editor, Category = AssetBrowserCategory }); + private string PageName(SettingsSection section) { + var root = Sections.FirstOrDefault(r => r.Children.Contains(section)); + return root?.Name ?? string.Empty; + } + + private static SettingsSection BuildRoot(SettingsPageModel page) { + var tab = page.Key switch { + PhysicsPage => SettingsTab.Physics, + RendererPage => SettingsTab.Rendering, + _ => SettingsTab.Group + }; + var root = new SettingsSection { Name = page.Title, Tab = tab, PageKey = page.Key }; + if (page.Cards.Count > 1 && !s_flatPages.Contains(page.Key)) + foreach (var card in page.Cards) + root.Children.Add(new SettingsSection { + Name = card.Title, + Tab = tab, + PageKey = page.Key, + CardKey = card.Key, + Category = card.Key + }); + + if (page.Key == PhysicsPage) + root.Children.Add(new SettingsSection { + Name = PhysicsLayersCategory, + Tab = SettingsTab.Physics, + PageKey = page.Key, + Category = PhysicsLayersCategory, + Extra = SettingsExtra.PhysicsLayers + }); + + if (page.Key == RendererPage) + root.Children.Add(new SettingsSection { + Name = BakingCategory, + Tab = SettingsTab.Rendering, + PageKey = page.Key, + Category = BakingCategory, + Extra = SettingsExtra.Baking + }); + return root; } - private static SettingsSection BuildRoot(string name, SettingsTab tab, List categories) { - var root = new SettingsSection { Name = name, Tab = tab }; - foreach (var category in categories) - root.Children.Add(new SettingsSection { Name = category.Name, Tab = tab, Category = category.Name }); + private static SettingsSection BuildEditorRoot(SettingsPageModel? preferences) { + var root = new SettingsSection { Name = "Editor", Tab = SettingsTab.Editor, PageKey = SettingsTree.EditorPage }; + if (preferences is not null) + foreach (var card in preferences.Cards) + root.Children.Add(new SettingsSection { + Name = card.Title, + Tab = SettingsTab.Editor, + PageKey = SettingsTree.EditorPage, + CardKey = card.Key, + Category = card.Key + }); + + root.Children.Add(new SettingsSection { + Name = AssetBrowserCategory, + Tab = SettingsTab.Editor, + PageKey = SettingsTree.EditorPage, + Category = AssetBrowserCategory, + Extra = SettingsExtra.AssetBrowser + }); return root; } @@ -151,46 +340,98 @@ private static string SavePathOfProject() { : ""; } - private void OpenProjectSettingsFile() { - if (!ProjectContext.IsInitialized) return; + private void RebuildCards() { + Cards.Clear(); - var realPath = Directory.EnumerateFiles(ProjectContext.ProjectPath, "*.toast").FirstOrDefault(); - if (realPath is null) { - StatusMessage = "No .toast project file found at the project root"; - return; + if (SelectedSection is { Extra: SettingsExtra.None, PageKey: { } pageKey } section) { + var page = m_pages.FirstOrDefault(p => p.Key == pageKey); + if (page is not null) + foreach (var card in page.Cards.Where(c => section.CardKey is null || c.Key == section.CardKey)) { + var withInfo = pageKey == ProjectPage && card.Key == "project/"; + Cards.Add(new SettingsCardViewModel(card, pageKey, page.Cards.IndexOf(card), withInfo ? ProjectInfo : null)); + } } - var virtualPath = ProjectContext.ToVirtual(realPath) ?? realPath; - var definition = AssetTypeRegistry.All.OfType().FirstOrDefault(); - if (definition is null) return; + ApplyFilter(); + } + + private void ApplyFilter() { + var query = SearchText.Trim(); + foreach (var card in Cards) card.ApplyFilter(query, true, true); + + foreach (var empty in Cards.Where(c => !c.IsVisible).ToList()) Cards.Remove(empty); + + OnPropertyChanged(nameof(NothingToShow)); + OnPropertyChanged(nameof(IsSearching)); + OnPropertyChanged(nameof(EmptyMessage)); + } + + partial void OnSelectedSectionChanged(SettingsSection? value) { + RebuildCards(); + OnPropertyChanged(nameof(ActiveExtra)); + OnPropertyChanged(nameof(ShowPhysicsLayers)); + foreach (var item in m_navItems.Values) item.IsSelected = value is not null && item.Section == value; + OnPropertyChanged(nameof(IsPhysicsLayers)); + OnPropertyChanged(nameof(IsAssetBrowser)); + OnPropertyChanged(nameof(ShowAssetBrowser)); + OnPropertyChanged(nameof(ShowBaking)); + OnPropertyChanged(nameof(ShowCards)); + OnPropertyChanged(nameof(SectionTitle)); + OnPropertyChanged(nameof(NothingToShow)); + } - GeneralEditor.OpenFile(Path.GetFileNameWithoutExtension(realPath), virtualPath, definition); + partial void OnSearchTextChanged(string value) => ReapplyFilter(); + + private void ReapplyFilter() { + RebuildCards(); + OnPropertyChanged(nameof(NothingToShow)); } - private void RefreshVisibleCategories() { - VisibleCategories.Clear(); - if (SelectedSection is not { } section || section.Tab is SettingsTab.General or SettingsTab.Editor) return; + private void RebuildNav() { + var open = m_navItems.Where(p => p.Value.Depth == 0).GroupBy(p => p.Key.Name + "/" + p.Key.PageKey) + .ToDictionary(g => g.Key, g => g.First().Value.IsExpanded); + m_navItems.Clear(); + foreach (var root in Sections) { + var item = new SettingsNavItem(root, 0); + if (open.TryGetValue(root.Name + "/" + root.PageKey, out var expanded)) item.IsExpanded = expanded; + m_navItems[root] = item; + foreach (var child in root.Children) m_navItems[child] = new SettingsNavItem(child, 1); + } + + SyncNavRows(); + } - var prefix = section.Tab == SettingsTab.Rendering ? RendererPrefix : PhysicsPrefix; - foreach (var category in SettingRowFactory.BuildCategories(prefix)) { - if (section.Category is null || section.Category == category.Name) VisibleCategories.Add(category); + private void SyncNavRows() { + NavRows.Clear(); + foreach (var root in Sections) { + NavRows.Add(m_navItems[root]); + if (!m_navItems[root].IsExpanded) continue; + foreach (var child in root.Children) NavRows.Add(m_navItems[child]); } + + foreach (var item in m_navItems.Values) item.IsSelected = SelectedSection is not null && item.Section == SelectedSection; } - partial void OnSelectedSectionChanged(SettingsSection? value) { - RefreshVisibleCategories(); - OnPropertyChanged(nameof(ActiveTab)); - OnPropertyChanged(nameof(IsGeneral)); - OnPropertyChanged(nameof(IsRendering)); - OnPropertyChanged(nameof(IsPhysics)); - OnPropertyChanged(nameof(IsEditor)); - OnPropertyChanged(nameof(IsEngineTab)); - OnPropertyChanged(nameof(IsPhysicsTags)); - OnPropertyChanged(nameof(IsSettingList)); + public void SelectNav(SettingsNavItem item) { + SelectedSection = item.Section; + if (item.Depth == 0 && !item.IsExpanded) { + item.IsExpanded = true; + SyncNavRows(); + } + } + + public void ToggleNav(SettingsNavItem item) { + item.IsExpanded = !item.IsExpanded; + SyncNavRows(); + } + + private void RefreshLive() { + foreach (var row in Cards.SelectMany(c => c.AllRows)) row.Reload(false); + RefreshStatus(); } private void RefreshStatus() { - if (!IsRendering) return; + if (!ShowBaking) return; StaleReflectionProbes = ToastRenderer.StaleReflectionProbes; StaleIrradianceVolumes = ToastRenderer.StaleIrradianceVolumes; IrradianceProbeCount = ToastRenderer.IrradianceProbeCount; @@ -206,11 +447,8 @@ private void Save() { [RelayCommand] private void ResetAll() { ToastSettings.ResetAll(); - foreach (var category in VisibleCategories) - foreach (var row in category.Rows) - row.Reload(); + foreach (var row in Cards.SelectMany(c => c.AllRows)) row.Reload(); PhysicsLayers.Reload(); - StatusMessage = "Reset to defaults"; } @@ -220,6 +458,11 @@ private void Reload() { StatusMessage = "Reloaded from the engine"; } + [RelayCommand] + private void ClearSearch() { + SearchText = string.Empty; + } + [RelayCommand] private void BakeReflectionProbes() { ToastRenderer.BakeReflectionProbes(); diff --git a/editor/Workspace/ProjectSettingsWindow.cs b/editor/Workspace/ProjectSettingsWindow.cs index c16793d12..3da0ae590 100644 --- a/editor/Workspace/ProjectSettingsWindow.cs +++ b/editor/Workspace/ProjectSettingsWindow.cs @@ -1,16 +1,25 @@ using Avalonia.Controls; +using editor.Settings; namespace editor.Workspace; public sealed class ProjectSettingsWindow : Window { public ProjectSettingsWindow(ProjectSettingsViewModel viewModel) { + var state = SettingsPanelState.Current; Title = "Project Settings"; - Width = 1200; - Height = 800; - MinWidth = 800; - MinHeight = 560; + Width = state.WindowWidth; + Height = state.WindowHeight; + MinWidth = 640; + MinHeight = 460; WindowStartupLocation = WindowStartupLocation.CenterOwner; DataContext = viewModel; Content = new ProjectSettingsView { DataContext = viewModel }; + + Closing += (_, _) => { + if (WindowState != WindowState.Normal) return; + state.WindowWidth = Width; + state.WindowHeight = Height; + state.Save(); + }; } } diff --git a/editor/Workspace/RendererSettingsView.axaml b/editor/Workspace/RendererSettingsView.axaml deleted file mode 100644 index 1cdc73169..000000000 --- a/editor/Workspace/RendererSettingsView.axaml +++ /dev/null @@ -1,197 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/editor/Workspace/RendererSettingsView.axaml.cs b/editor/Workspace/RendererSettingsView.axaml.cs deleted file mode 100644 index 0263818e7..000000000 --- a/editor/Workspace/RendererSettingsView.axaml.cs +++ /dev/null @@ -1,25 +0,0 @@ -// -// RendererSettingsView.axaml.cs -// 16 Aug 2026 -// - -using Avalonia.Controls; -using Avalonia.Markup.Xaml; - -namespace editor.Workspace; - -public partial class RendererSettingsView : UserControl { - public RendererSettingsView() { - InitializeComponent(); - - // The rows cannot be built when the view model is constructed: the dock creates its tools as the shell - // starts, before a workspace exists and therefore before the renderer has declared anything. Attaching - // is the first moment the panel is actually being looked at, which is late enough - AttachedToVisualTree += (_, _) => (DataContext as RendererSettingsViewModel)?.StartPolling(); - DetachedFromVisualTree += (_, _) => (DataContext as RendererSettingsViewModel)?.StopPolling(); - } - - private void InitializeComponent() { - AvaloniaXamlLoader.Load(this); - } -} diff --git a/editor/Workspace/RendererSettingsViewModel.cs b/editor/Workspace/RendererSettingsViewModel.cs deleted file mode 100644 index aa163f8cc..000000000 --- a/editor/Workspace/RendererSettingsViewModel.cs +++ /dev/null @@ -1,126 +0,0 @@ -// -// RendererSettingsViewModel.cs -// 16 Aug 2026 -// - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Avalonia.Threading; -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; -using Dock.Model.Mvvm.Controls; -using editor.Engine; - -namespace editor.Workspace; - -/// -/// The renderer's settings and bake actions, replacing the ImGui debug panel -/// -/// -/// The rows are generated from whatever the engine declared under the "renderer." prefix, so a knob added in -/// C++ appears here with no change to this file. Another system wanting its own panel changes the prefix - -/// that is the whole extension point -/// -/// Values are written through to the engine as they are edited, which is what makes the viewport respond -/// live. Persisting them is separate and explicit: Save writes the layer the editor is authoring, which for -/// the editor is the project layer that ships as the game's defaults -/// -public partial class RendererSettingsViewModel : Tool { - private const string KeyPrefix = "renderer."; - - /// A bake's progress is only visible through counters the render thread updates, so the panel polls while - /// it is on screen rather than the renderer pushing an event for something only this window reads - private readonly DispatcherTimer m_statusTimer; - - [ObservableProperty] private uint m_irradianceProbeCount; - [ObservableProperty] private bool m_rayTracingSupported; - [ObservableProperty] private string m_savePath = string.Empty; - [ObservableProperty] private string m_statusMessage = string.Empty; - [ObservableProperty] private uint m_staleIrradianceVolumes; - [ObservableProperty] private uint m_staleReflectionProbes; - - public RendererSettingsViewModel() { - Categories = []; - - m_statusTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1.0) }; - m_statusTimer.Tick += (_, _) => RefreshStatus(); - } - - public ObservableCollection Categories { get; } - - public bool HasStaleReflectionProbes => StaleReflectionProbes > 0; - public bool HasStaleIrradianceVolumes => StaleIrradianceVolumes > 0; - - /// Rebuilds the rows from the engine's registry - /// - /// Deferred until the panel is first shown rather than done in the constructor: the dock builds its tools - /// as the shell starts, which is before the renderer exists and therefore before anything under - /// "renderer." has been declared. Calling it again is how the panel picks up a later declaration - /// - public void Load() { - Categories.Clear(); - foreach (var category in SettingRowFactory.BuildCategories(KeyPrefix)) Categories.Add(category); - - SavePath = ToastSettings.ActivePath; - RayTracingSupported = ToastRenderer.SupportsRayTracing; - RefreshStatus(); - - StatusMessage = Categories.Count == 0 - ? "No renderer settings declared yet - open a workspace so the renderer starts." - : string.Empty; - } - - public void StartPolling() { - if (Categories.Count == 0) Load(); - m_statusTimer.Start(); - } - - public void StopPolling() { - m_statusTimer.Stop(); - } - - private void RefreshStatus() { - StaleReflectionProbes = ToastRenderer.StaleReflectionProbes; - StaleIrradianceVolumes = ToastRenderer.StaleIrradianceVolumes; - IrradianceProbeCount = ToastRenderer.IrradianceProbeCount; - OnPropertyChanged(nameof(HasStaleReflectionProbes)); - OnPropertyChanged(nameof(HasStaleIrradianceVolumes)); - } - - [RelayCommand] - private void Save() { - StatusMessage = ToastSettings.Save() ? $"Saved to {ToastSettings.ActivePath}" : "Save failed - see the log"; - } - - /// Drops every override in the active layer, exposing the defaults underneath - [RelayCommand] - private void ResetAll() { - ToastSettings.ResetAll(); - foreach (var category in Categories) - foreach (var row in category.Rows) - row.Reload(); - - StatusMessage = "Reset to defaults - not saved yet"; - } - - [RelayCommand] - private void Reload() { - Load(); - StatusMessage = "Reloaded from the engine"; - } - - [RelayCommand] - private void BakeReflectionProbes() { - ToastRenderer.BakeReflectionProbes(); - StatusMessage = "Baking reflection probes - six frames per probe, shown in the viewport"; - } - - [RelayCommand] - private void BakeIrradianceVolumes() { - ToastRenderer.BakeIrradianceVolumes(); - StatusMessage = IrradianceProbeCount > 0 - ? $"Baking {IrradianceProbeCount} irradiance probes - {IrradianceProbeCount * 6} frames" - : "No irradiance volumes registered in this scene"; - } -} diff --git a/editor/Workspace/SettingRowViewModels.cs b/editor/Workspace/SettingRowViewModels.cs deleted file mode 100644 index 4deebff00..000000000 --- a/editor/Workspace/SettingRowViewModels.cs +++ /dev/null @@ -1,320 +0,0 @@ -// -// SettingRowViewModels.cs -// 16 Aug 2026 -// - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; -using editor.Engine; - -namespace editor.Workspace; - -/// -/// Base for one editable row in a settings panel -/// -/// -/// One subclass per widget shape rather than one row with a mode flag, because the view picks its template by -/// row type - which keeps the type test in XAML's DataTemplates where Avalonia already does it, instead of in -/// a converter that has to be kept in step with the engine's Type enum -/// -public abstract partial class SettingRow : ObservableObject { - protected SettingRow(SettingDescriptor descriptor) { - Descriptor = descriptor; - } - - /// Set while Reload() assigns, so the setter does not echo the engine's own value back at it - /// - /// Every row writes through on change, which is what makes the viewport respond live. Reload() is the one - /// path that assigns a value the engine already holds - after a reset, or when the panel re-reads - and - /// writing that back would mark the settings dirty for a change nobody made - /// - protected bool SuppressWrite; - - public SettingDescriptor Descriptor { get; } - - public string Key => Descriptor.Key; - public virtual string Label => Descriptor.Label; - public string Description => Descriptor.Description; - public bool HasDescription => !string.IsNullOrWhiteSpace(Descriptor.Description); - public bool RequiresRestart => Descriptor.RequiresRestart; - - /// Drops the active layer's override, then shows whatever was underneath it - [RelayCommand] - private void Reset() { - ResetValue(); - Reload(); - } - - protected virtual void ResetValue() { - ToastSettings.Reset(Key); - } - - /// Re-reads the engine's value without writing anything back - public abstract void Reload(); -} - -public sealed partial class BoolSettingRow : SettingRow { - [ObservableProperty] private bool m_value; - - public BoolSettingRow(SettingDescriptor descriptor) : base(descriptor) { - m_value = ToastSettings.GetBool(descriptor.Key); - } - - partial void OnValueChanged(bool value) { - if (SuppressWrite) return; - ToastSettings.SetBool(Key, value); - } - - public override void Reload() { - SuppressWrite = true; - Value = ToastSettings.GetBool(Key); - SuppressWrite = false; - } -} - -public sealed partial class FloatSettingRow : SettingRow { - [ObservableProperty] private double m_value; - - public FloatSettingRow(SettingDescriptor descriptor) : base(descriptor) { - m_value = ToastSettings.GetFloat(descriptor.Key); - } - - public double Minimum => Descriptor.HasRange ? Descriptor.Min : double.MinValue; - public double Maximum => Descriptor.HasRange ? Descriptor.Max : double.MaxValue; - - /// A slider needs a tick; the engine only supplies one when the natural increment is not obvious - public double Increment => Descriptor.Step > 0.0 - ? Descriptor.Step - : Descriptor.HasRange - ? (Descriptor.Max - Descriptor.Min) / 200.0 - : 0.01; - - public bool UseSlider => Descriptor.HasRange; - - public float FloatValue { - get => (float)Value; - set => Value = value; - } - - partial void OnValueChanged(double value) { - OnPropertyChanged(nameof(FloatValue)); - if (SuppressWrite) return; - ToastSettings.SetFloat(Key, value); - } - - public override void Reload() { - SuppressWrite = true; - Value = ToastSettings.GetFloat(Key); - SuppressWrite = false; - } -} - -public sealed partial class IntSettingRow : SettingRow { - [ObservableProperty] private decimal m_value; - - public IntSettingRow(SettingDescriptor descriptor) : base(descriptor) { - m_value = ToastSettings.GetInt(descriptor.Key); - } - - public decimal Minimum => Descriptor.HasRange ? (decimal)Descriptor.Min : decimal.MinValue; - public decimal Maximum => Descriptor.HasRange ? (decimal)Descriptor.Max : decimal.MaxValue; - public decimal Increment => Descriptor.Step > 0.0 ? (decimal)Descriptor.Step : 1m; - - public int IntValue { - get => (int)Value; - set => Value = value; - } - - public double MinimumDouble => (double)Minimum; - - public double MaximumDouble => (double)Maximum; - - partial void OnValueChanged(decimal value) { - OnPropertyChanged(nameof(IntValue)); - if (SuppressWrite) return; - ToastSettings.SetInt(Key, (long)value); - } - - public override void Reload() { - SuppressWrite = true; - Value = ToastSettings.GetInt(Key); - SuppressWrite = false; - } -} - -/// An integer setting the engine gave a name list, shown as a combo box over that list -public sealed partial class EnumSettingRow : SettingRow { - [ObservableProperty] private int m_selectedIndex; - - public EnumSettingRow(SettingDescriptor descriptor) : base(descriptor) { - Options = new ObservableCollection(descriptor.Options); - m_selectedIndex = ClampIndex((int)ToastSettings.GetInt(descriptor.Key)); - } - - public ObservableCollection Options { get; } - - partial void OnSelectedIndexChanged(int value) { - // The combo reports -1 while it rebuilds its items; writing that through would store an index no option - // answers to, and the engine would clamp it to something the user never picked - if (value < 0 || SuppressWrite) return; - ToastSettings.SetInt(Key, value); - } - - public override void Reload() { - SuppressWrite = true; - SelectedIndex = ClampIndex((int)ToastSettings.GetInt(Key)); - SuppressWrite = false; - } - - private int ClampIndex(int index) { - return Options.Count == 0 ? -1 : Math.Clamp(index, 0, Options.Count - 1); - } -} - -public sealed partial class StringSettingRow : SettingRow { - [ObservableProperty] private string m_value; - - public StringSettingRow(SettingDescriptor descriptor) : base(descriptor) { - m_value = ToastSettings.GetString(descriptor.Key); - } - - partial void OnValueChanged(string value) { - if (SuppressWrite) return; - ToastSettings.SetString(Key, value); - } - - public override void Reload() { - SuppressWrite = true; - Value = ToastSettings.GetString(Key); - SuppressWrite = false; - } -} - -public sealed partial class AssetSettingRow : SettingRow { - [ObservableProperty] private string m_value; - - public AssetSettingRow(SettingDescriptor descriptor) : base(descriptor) { - m_value = ToastSettings.GetString(descriptor.Key); - } - - public string AssetType => Descriptor.AssetType; - - partial void OnValueChanged(string value) { - if (SuppressWrite) return; - ToastSettings.SetString(Key, value ?? string.Empty); - } - - public override void Reload() { - SuppressWrite = true; - Value = ToastSettings.GetString(Key); - SuppressWrite = false; - } -} - -public sealed partial class Vec3SettingRow : SettingRow { - private readonly SettingDescriptor[] m_axes; - [ObservableProperty] private float m_x; - [ObservableProperty] private float m_y; - [ObservableProperty] private float m_z; - - public Vec3SettingRow(SettingDescriptor x, SettingDescriptor y, SettingDescriptor z) : base(x) { - m_axes = [x, y, z]; - m_x = (float)ToastSettings.GetFloat(x.Key); - m_y = (float)ToastSettings.GetFloat(y.Key); - m_z = (float)ToastSettings.GetFloat(z.Key); - Label = StripAxis(x.Label); - } - - public override string Label { get; } - - partial void OnXChanged(float value) => Write(0, value); - partial void OnYChanged(float value) => Write(1, value); - partial void OnZChanged(float value) => Write(2, value); - - private void Write(int axis, float value) { - if (SuppressWrite) return; - ToastSettings.SetFloat(m_axes[axis].Key, value); - } - - protected override void ResetValue() { - foreach (var axis in m_axes) ToastSettings.Reset(axis.Key); - } - - public override void Reload() { - SuppressWrite = true; - X = (float)ToastSettings.GetFloat(m_axes[0].Key); - Y = (float)ToastSettings.GetFloat(m_axes[1].Key); - Z = (float)ToastSettings.GetFloat(m_axes[2].Key); - SuppressWrite = false; - } - - /// "Gravity X" -> "Gravity" - private static string StripAxis(string label) { - return label.EndsWith(" X", StringComparison.Ordinal) ? label[..^2] : label; - } - - /// The key without its _x suffix when @p x, @p y and @p z are the three axes of one vector - public static string? StemOf(SettingDescriptor x, SettingDescriptor y, SettingDescriptor z) { - if (x.Type != SettingType.Float || y.Type != SettingType.Float || z.Type != SettingType.Float) return null; - if (x.Category != y.Category || x.Category != z.Category) return null; - if (!x.Key.EndsWith("_x", StringComparison.Ordinal)) return null; - var stem = x.Key[..^2]; - return y.Key == stem + "_y" && z.Key == stem + "_z" ? stem : null; - } -} - -/// One collapsible group of rows, named by the engine's Meta::category -public sealed class SettingCategory { - public required string Name { get; init; } - public required IReadOnlyList Rows { get; init; } -} - -/// Builds rows from whatever the engine declared -public static class SettingRowFactory { - /// Restricts the panel to one system's settings, e.g. "renderer." - public static List BuildCategories(string keyPrefix) { - var byCategory = new Dictionary>(); - var order = new List(); - - var descriptors = ToastSettings.Enumerate() - .Where(d => !d.Hidden && - (string.IsNullOrEmpty(keyPrefix) || d.Key.StartsWith(keyPrefix, StringComparison.Ordinal))) - .ToList(); - - for (var i = 0; i < descriptors.Count; i++) { - var descriptor = descriptors[i]; - - SettingRow row; - if (i + 2 < descriptors.Count && - Vec3SettingRow.StemOf(descriptor, descriptors[i + 1], descriptors[i + 2]) is not null) { - row = new Vec3SettingRow(descriptor, descriptors[i + 1], descriptors[i + 2]); - i += 2; - } else row = descriptor switch { - { IsEnum: true } => new EnumSettingRow(descriptor), - { Type: SettingType.Bool } => new BoolSettingRow(descriptor), - { Type: SettingType.Int } => new IntSettingRow(descriptor), - { Type: SettingType.Float } => new FloatSettingRow(descriptor), - { Type: SettingType.String, AssetType.Length: > 0 } => new AssetSettingRow(descriptor), - _ => new StringSettingRow(descriptor) - }; - - if (!byCategory.TryGetValue(descriptor.Category, out var rows)) { - rows = []; - byCategory[descriptor.Category] = rows; - order.Add(descriptor.Category); - } - - rows.Add(row); - } - - // Declaration order, not alphabetical: the engine declares display and quality before the per-effect - // detail, which is the order someone actually wants to read them in - var result = new List(order.Count); - foreach (var name in order) result.Add(new SettingCategory { Name = name, Rows = byCategory[name] }); - return result; - } -} diff --git a/editor/Workspace/ViewportControl.axaml.cs b/editor/Workspace/ViewportControl.axaml.cs index 1ea70e059..d6e080f4c 100644 --- a/editor/Workspace/ViewportControl.axaml.cs +++ b/editor/Workspace/ViewportControl.axaml.cs @@ -808,10 +808,26 @@ protected override void OnKeyDown(KeyEventArgs e) { // RenderDoc-only check meant F12 silently did nothing for a Nsight-only session if (e.Key == Key.F12) { if (m_engine is not null) Events.Send(new CaptureFrame()); + + SendKey(e, ActionPressed); e.Handled = true; return; } + if (ToastEngine.ConsoleOpen) { + var sent = SendKey(e, ActionPressed); + + m_consoleTextSent = false; + if (!e.KeyModifiers.HasFlag(KeyModifiers.Control) && !e.KeyModifiers.HasFlag(KeyModifiers.Alt) && + !string.IsNullOrEmpty(e.KeySymbol) && !char.IsControl(e.KeySymbol[0])) { + foreach (var rune in e.KeySymbol.AsSpan().EnumerateRunes()) Events.Send(new WindowChar { Key = (uint)rune.Value }); + m_consoleTextSent = true; + } + + if (sent || m_consoleTextSent) e.Handled = true; + return; + } + // backtick frees the mouse during play; never forwarded to the game if (PlayMode && e.Key == Key.OemTilde) { ReleaseHeldInput(); @@ -840,12 +856,17 @@ protected override void OnKeyDown(KeyEventArgs e) { protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); - // matches the OnKeyDown intercept - F12 down is never forwarded, so its key-up shouldn't be either if (e.Key == Key.F12) { + SendKey(e, ActionReleased); e.Handled = true; return; } + if (ToastEngine.ConsoleOpen) { + if (SendKey(e, ActionReleased)) e.Handled = true; + return; + } + if (HandleFlyKey(e, false)) { e.Handled = true; return; @@ -862,7 +883,7 @@ private void OnSwallowedAlt(object? sender, KeyEventArgs e) { } // F3 still reaches the engine after the backtick freed the mouse - private bool IsOverlayKey(Key key) => PlayMode && key == Key.F3; + private bool IsOverlayKey(Key key) => key == Key.F12 || (PlayMode && key == Key.F3) || ToastEngine.ConsoleOpen; private bool SendKey(KeyEventArgs e, int action) { var wasHeld = action == ActionReleased && m_heldKeys.Remove(e.Key); @@ -878,15 +899,21 @@ private bool SendKey(KeyEventArgs e, int action) { return true; } + private bool m_consoleTextSent; + protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); - if (!ShouldForward || m_engine is null || string.IsNullOrEmpty(e.Text)) return; + if (m_consoleTextSent) { + m_consoleTextSent = false; + return; + } + if ((!ShouldForward && !ToastEngine.ConsoleOpen) || m_engine is null || string.IsNullOrEmpty(e.Text)) return; foreach (var rune in e.Text.AsSpan().EnumerateRunes()) Events.Send(new WindowChar { Key = (uint)rune.Value }); } private async Task PasteClipboardAsync() { - if (!ShouldForward || m_engine is null) return; + if ((!ShouldForward && !ToastEngine.ConsoleOpen) || m_engine is null) return; var clipboard = m_topLevel?.Clipboard; if (clipboard is null) return; var data = await clipboard.TryGetDataAsync(); @@ -961,6 +988,10 @@ private static (int key, int scancode) MapKey(Key k) { Key.F10 => (ScancodeMask | 67, 67), Key.F11 => (ScancodeMask | 68, 68), Key.F12 => (ScancodeMask | 69, 69), + Key.Home => (ScancodeMask | 74, 74), + Key.End => (ScancodeMask | 77, 77), + Key.PageUp => (ScancodeMask | 75, 75), + Key.PageDown => (ScancodeMask | 78, 78), _ => (0, 0) }; } diff --git a/editor/Workspace/WorkspaceViewModel.cs b/editor/Workspace/WorkspaceViewModel.cs index 21026f2c2..6638dfc16 100644 --- a/editor/Workspace/WorkspaceViewModel.cs +++ b/editor/Workspace/WorkspaceViewModel.cs @@ -53,13 +53,13 @@ public partial class WorkspaceViewModel : Document, IAutosavable, IDisposable { [ObservableProperty] private PlayState m_playState; private PlayWindow? m_playWindow; - [ObservableProperty] private double m_rotateSnap = 30; - [ObservableProperty] private bool m_rotateSnapEnabled = true; - [ObservableProperty] private double m_scaleSnap = 0.10; - [ObservableProperty] private bool m_scaleSnapEnabled = true; - [ObservableProperty] private double m_translateSnap = 0.10; + [ObservableProperty] private double m_rotateSnap = ToastSettings.Number("editor.snapping.rotate_step", 30); + [ObservableProperty] private bool m_rotateSnapEnabled = ToastSettings.Flag("editor.snapping.rotate_enabled", true); + [ObservableProperty] private double m_scaleSnap = ToastSettings.Number("editor.snapping.scale_step", 0.10); + [ObservableProperty] private bool m_scaleSnapEnabled = ToastSettings.Flag("editor.snapping.scale_enabled", true); + [ObservableProperty] private double m_translateSnap = ToastSettings.Number("editor.snapping.translate_step", 0.10); - [ObservableProperty] private bool m_translateSnapEnabled = true; + [ObservableProperty] private bool m_translateSnapEnabled = ToastSettings.Flag("editor.snapping.translate_enabled", true); private WorkspaceViewModel(ToastEngine? engine = null) { Engine = engine; @@ -420,6 +420,8 @@ private void SetGameCamera(bool value) { public static event Action? PlayModeChanged; partial void OnPlayStateChanged(PlayState value) { + ToastSettings.Restore(); + OnPropertyChanged(nameof(IsPlaying)); OnPropertyChanged(nameof(IsSimulating)); OnPropertyChanged(nameof(IsPlayingInViewport)); @@ -441,6 +443,7 @@ partial void OnPlayStateChanged(PlayState value) { } partial void OnIsPausedChanged(bool value) { + ToastSettings.Restore(); UpdateAdvancing(); if (PlayHandle != 0) Events.Send(new WorkspacePause { Handle = PlayHandle, Paused = value }); TogglePlayCommand.NotifyCanExecuteChanged(); diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 35cdf35f0..faf0cc8f1 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -113,7 +113,7 @@ target_link_libraries(toast_engine LZ4::lz4 unofficial::sqlite3::sqlite3 toast_pack - $<$,$>:imgui::imgui> + imgui::imgui RmlUi::Core cpptrace::cpptrace $<$:${EXTERNAL_LIBS_DEBUG}> diff --git a/engine/assets/schemas/project_settings.schema.json b/engine/assets/schemas/project_settings.schema.json index 79d8af4c4..1a9c5f4ac 100644 --- a/engine/assets/schemas/project_settings.schema.json +++ b/engine/assets/schemas/project_settings.schema.json @@ -13,61 +13,11 @@ "type": "array", "x-toast-type": "int[]", "description": "Project version as [major, minor, patch]", - "default": [1, 0, 0] - }, - "databases": { - "type": "array", - "x-toast-type": "string[]", - "description": "Each entry X creates an X:// VFS scheme rooted at {ProjectPath}/X", - "default": ["assets"] - }, - "max_tick_rate": { - "type": "integer", - "x-toast-type": "int", - "minimum": 0, - "description": "Maximum game ticks per second in the editor and the player; 0 is uncapped", - "default": 500 - }, - "gameplay": { - "x-toast-type": "gameplay", - "description": "Gameplay entry-point settings" - }, - "ui": { - "x-toast-type": "ui", - "description": "UI settings" - } - }, - "definitions": { - "ui": { - "type": "object", - "properties": { - "color_scheme": { - "x-toast-type": "asset", - "x-toast-asset-type": "color_scheme", - "description": "Global color scheme used as the fallback for ${color:...} formatting" - }, - "languages": { - "type": "array", - "x-toast-type": "string[]", - "description": "Supported localization languages; the first entry is the default", - "default": ["en"] - } - } - }, - "gameplay": { - "type": "object", - "properties": { - "init_scene": { - "x-toast-type": "asset", - "x-toast-asset-type": "node", - "description": "Initial scene loaded when the game starts" - }, - "player": { - "x-toast-type": "asset", - "x-toast-asset-type": "node", - "description": "Player prefab spawned at game start" - } - } + "default": [ + 1, + 0, + 0 + ] } } } diff --git a/engine/assets/ui/fonts/FiraCodeNerdFont-Regular.ttf b/engine/assets/ui/fonts/FiraCodeNerdFont-Regular.ttf new file mode 100644 index 000000000..fd066170f Binary files /dev/null and b/engine/assets/ui/fonts/FiraCodeNerdFont-Regular.ttf differ diff --git a/engine/assets/ui/fonts/FiraCodeNerdFont-Regular.ttf.meta b/engine/assets/ui/fonts/FiraCodeNerdFont-Regular.ttf.meta new file mode 100644 index 000000000..243035847 --- /dev/null +++ b/engine/assets/ui/fonts/FiraCodeNerdFont-Regular.ttf.meta @@ -0,0 +1,4 @@ +uid = "Fc0d3N3rdRg" +type = "font" +created_at = "2026-11-24T12:00:00.0000000Z" +modified_at = "2026-11-24T12:00:00.0000000Z" diff --git a/engine/ffi/engine.h b/engine/ffi/engine.h index cd8fa71c3..a7e692a48 100644 --- a/engine/ffi/engine.h +++ b/engine/ffi/engine.h @@ -167,6 +167,8 @@ TOAST_C_API void toast_set_show_debug_windows(int visible) NOEXCEPT; /// @return 1 while the debug overlay is up in game view and the cursor must stay free TOAST_C_API int toast_debug_overlay_owns_cursor(void) NOEXCEPT; +TOAST_C_API int toast_console_is_open(void) NOEXCEPT; + /// @brief Tells the renderer whether the host application is focused and whether it is minimized /// @param focused 0 holds rendering at 30 fps (or the configured cap when lower), 1 restores the configured cap /// @param minimized 1 stops rendering entirely until called again with 0 diff --git a/engine/ffi/settings.h b/engine/ffi/settings.h index 7795bc131..f0216a674 100644 --- a/engine/ffi/settings.h +++ b/engine/ffi/settings.h @@ -2,7 +2,6 @@ /// @author dario /// @date 16/08/2026 /// -/// @brief C surface over toast::settings::Settings /// #pragma once @@ -14,12 +13,22 @@ extern "C" { #endif -/// Mirrors toast::settings::Type enum toast_setting_type { TOAST_SETTING_BOOL = 0, TOAST_SETTING_INT = 1, TOAST_SETTING_FLOAT = 2, TOAST_SETTING_STRING = 3, + TOAST_SETTING_VEC2 = 4, + TOAST_SETTING_VEC3 = 5, + TOAST_SETTING_VEC4 = 6, + TOAST_SETTING_QUAT = 7, +}; + +enum toast_setting_kind { + TOAST_SETTING_KIND_NORMAL = 0, + TOAST_SETTING_KIND_ADVANCED = 1, + TOAST_SETTING_KIND_DEBUG = 2, + TOAST_SETTING_KIND_USER = 3, }; /** @@ -41,6 +50,9 @@ typedef struct { int32_t option_count; ///< Non-zero makes an int setting a combo box; read with toast_settings_get_option int32_t requires_restart; int32_t hidden; + int32_t kind; + int32_t is_array; + int32_t value_type; } toast_setting_desc; TOAST_C_API int32_t toast_settings_count(void) NOEXCEPT; @@ -51,6 +63,8 @@ TOAST_C_API int32_t toast_settings_get_desc(int32_t index, toast_setting_desc* o /// @return the asset type a string setting picks, or an empty string for a plain one TOAST_C_API const char* toast_settings_get_asset_type(int32_t index) NOEXCEPT; +TOAST_C_API const char* toast_settings_get_unit(int32_t index) NOEXCEPT; + /// @return option @p option of setting @p index, or NULL when either is out of range TOAST_C_API const char* toast_settings_get_option(int32_t index, int32_t option) NOEXCEPT; @@ -66,7 +80,6 @@ TOAST_C_API void toast_settings_set_int(const char* key, int64_t value) NOEXCEPT TOAST_C_API void toast_settings_set_float(const char* key, double value) NOEXCEPT; TOAST_C_API void toast_settings_set_string(const char* key, const char* value) NOEXCEPT; -/// @brief Drops the active layer's override for @p key, exposing the value underneath it TOAST_C_API void toast_settings_reset(const char* key) NOEXCEPT; TOAST_C_API void toast_settings_reset_all(void) NOEXCEPT; @@ -74,9 +87,22 @@ TOAST_C_API void toast_settings_reset_all(void) NOEXCEPT; TOAST_C_API int32_t toast_settings_save(void) NOEXCEPT; TOAST_C_API int32_t toast_settings_is_dirty(void) NOEXCEPT; -/// @return where the active layer writes, in a buffer valid until this thread's next call to it TOAST_C_API const char* toast_settings_active_path(void) NOEXCEPT; +TOAST_C_API const char* toast_settings_get_text(const char* key) NOEXCEPT; + +TOAST_C_API const char* toast_settings_get_default_text(const char* key) NOEXCEPT; + +TOAST_C_API int32_t toast_settings_set_text(const char* key, const char* text) NOEXCEPT; + +TOAST_C_API const char* toast_settings_last_error(void) NOEXCEPT; + +TOAST_C_API int32_t toast_settings_is_overridden(const char* key) NOEXCEPT; + +TOAST_C_API void toast_settings_restore(void) NOEXCEPT; + +TOAST_C_API int32_t toast_settings_cook(const char* config_dir, const char* toast_file, const char* stage_dir) NOEXCEPT; + #ifdef __cplusplus } #endif diff --git a/engine/src/toast/assets/asset_manager.cpp b/engine/src/toast/assets/asset_manager.cpp index 649899580..20a1a0cf6 100644 --- a/engine/src/toast/assets/asset_manager.cpp +++ b/engine/src/toast/assets/asset_manager.cpp @@ -540,6 +540,8 @@ void AssetManager::clearUnusedAssets() { } void AssetManager::setPaths(Paths&& paths) { + // worked out before project is moved from + roots["config"] = paths.config.empty() ? paths.project / "config" : std::move(paths.config); roots["project"] = std::move(paths.project); roots["artwork"] = std::move(paths.artworks); roots["cache"] = std::move(paths.cache); @@ -555,7 +557,7 @@ void AssetManager::clearDatabases() { // Keep only the five fixed special schemes; erase everything else std::erase_if(roots, [](const auto& kv) { const auto& k = kv.first; - return k != "project" && k != "artwork" && k != "cache" && k != "saved" && k != "core"; + return k != "project" && k != "artwork" && k != "cache" && k != "saved" && k != "core" && k != "config"; }); } @@ -565,6 +567,18 @@ auto AssetManager::projectRoot() -> const std::filesystem::path& { return it != roots.end() ? it->second : empty; } +auto AssetManager::configRoot() -> const std::filesystem::path& { + static const std::filesystem::path empty; + auto it = roots.find("config"); + return it != roots.end() ? it->second : empty; +} + +auto AssetManager::savedRoot() -> const std::filesystem::path& { + static const std::filesystem::path empty; + auto it = roots.find("saved"); + return it != roots.end() ? it->second : empty; +} + auto AssetManager::resolveVirtualPath(std::string_view virtual_path) -> std::optional { const auto sep = virtual_path.find("://"); if (sep == std::string_view::npos) { diff --git a/engine/src/toast/assets/asset_manager.hpp b/engine/src/toast/assets/asset_manager.hpp index 49953a451..c4badc596 100644 --- a/engine/src/toast/assets/asset_manager.hpp +++ b/engine/src/toast/assets/asset_manager.hpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -42,6 +43,7 @@ struct Paths { std::filesystem::path cache; std::filesystem::path saved; std::filesystem::path core; + std::filesystem::path config; }; /** @@ -53,6 +55,7 @@ struct Paths { * - cache:// generated or baked files that can be rebuilt * - core:// engine built-in assets (default shaders, primitives) * - saved:// user save data and preferences + * - config:// committed parameter files, `/config` unless the host says otherwise * * Content database schemes (registered via registerDatabase after ProjectSettings loads): * - assets:// default content database (always present for a new project) @@ -145,25 +148,29 @@ class AssetManager { * @param paths Filesystem paths for each fixed scheme (project, artwork, cache, core, saved) * @warning Not thread-safe after initialization; call this before creating the AssetManager or spawning load threads */ - static void setPaths(Paths&& paths); + TOAST_API static void setPaths(Paths&& paths); /** * @brief Registers a content database scheme * @note Call after setPaths and before AssetManager construction (or before reloadManifest) */ - static void registerDatabase(std::string_view name, std::filesystem::path root); + TOAST_API static void registerDatabase(std::string_view name, std::filesystem::path root); /** * @brief Removes all content database schemes (non-fixed), leaving only special roots intact * @note Used by reloadSettings to reset before re-registering databases from updated project settings */ - static void clearDatabases(); + TOAST_API static void clearDatabases(); /** * @brief Returns the project root path (project:// root) */ static auto projectRoot() -> const std::filesystem::path&; + TOAST_API static auto configRoot() -> const std::filesystem::path&; + + TOAST_API static auto savedRoot() -> const std::filesystem::path&; + /** * @brief Maps a virtual URI to its manifest UID * @param uri A string of the form scheme://relative/path diff --git a/engine/src/toast/assets/asset_params.cpp b/engine/src/toast/assets/asset_params.cpp new file mode 100644 index 000000000..bccf390bd --- /dev/null +++ b/engine/src/toast/assets/asset_params.cpp @@ -0,0 +1,10 @@ +#include "asset_params.hpp" + +namespace assets { + +auto assetParams() -> AssetParams& { + static AssetParams instance; + return instance; +} + +} diff --git a/engine/src/toast/assets/asset_params.hpp b/engine/src/toast/assets/asset_params.hpp new file mode 100644 index 000000000..2f7058338 --- /dev/null +++ b/engine/src/toast/assets/asset_params.hpp @@ -0,0 +1,53 @@ +/** + * @file asset_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief When assets reload + */ + +#pragma once +#include +#include +#include + +namespace assets { + +struct AssetParams : toast::params::Group<"assets"> { + using Kind = toast::params::Kind; + + bool hot_reload_enabled = param( + &hot_reload_enabled, "hot_reload.enabled", true, {.name = "Hot reload", .description = "Pick up files that changed on disk"} + ); + float hot_reload_interval = param( + &hot_reload_interval, "hot_reload.interval", 1.0F, + {.name = "Check every", .min = 0.1F, .max = 60.0F, .unit = "s", .description = "How often the disk is checked"} + ); + float unload_interval = param( + &unload_interval, "unload.interval", 30.0F, + {.name = "Free unused every", + .min = 0.0F, + .max = 3600.0F, + .unit = "s", + .description = "Assets nothing uses are released this often. 0 keeps them"} + ); + float skinned_bounds_padding = param( + &skinned_bounds_padding, "import.skinned_bounds_padding", 1.5F, + {.name = "Skinned bounds padding", + .min = 1.0F, + .max = 4.0F, + .description = "Culling bounds of skinned meshes grow by this much so animation does not pop out of view"} + ); + int32_t material_parent_depth = param( + &material_parent_depth, "materials.max_parent_depth", 16, + {.name = "Parent chain limit", + .min = 1, + .max = 64, + .kind = Kind::advanced, + .description = "Longest chain of parent materials before it counts as a loop"} + ); +}; + +TOAST_API auto assetParams() -> AssetParams&; + +} diff --git a/engine/src/toast/assets/material_instance.cpp b/engine/src/toast/assets/material_instance.cpp index 38eb195e1..c52f9568d 100644 --- a/engine/src/toast/assets/material_instance.cpp +++ b/engine/src/toast/assets/material_instance.cpp @@ -1,12 +1,13 @@ #include "material_instance.hpp" +#include "asset_params.hpp" + #include namespace assets { namespace { -constexpr int k_max_parent_depth = 16; thread_local int s_parent_depth = 0; struct DepthGuard { @@ -16,7 +17,7 @@ struct DepthGuard { [[nodiscard]] auto exceeded() const -> bool { - return s_parent_depth > k_max_parent_depth; + return s_parent_depth > assetParams().material_parent_depth; } }; diff --git a/engine/src/toast/assets/mesh.cpp b/engine/src/toast/assets/mesh.cpp index 510e2c200..36ec83d54 100644 --- a/engine/src/toast/assets/mesh.cpp +++ b/engine/src/toast/assets/mesh.cpp @@ -1,5 +1,7 @@ #include "mesh.hpp" +#include "asset_params.hpp" + #include namespace assets { @@ -134,8 +136,7 @@ auto Mesh::boundingSphere() const -> const glm::vec4& { } // See boundingSphere()'s docs: a skinned mesh is only ever measured in its bind pose here - constexpr float k_skinned_padding = 1.5f; - const float radius = std::sqrt(radius_squared) * (isSkinned() ? k_skinned_padding : 1.0f); + const float radius = std::sqrt(radius_squared) * (isSkinned() ? assetParams().skinned_bounds_padding : 1.0f); m_bounding_sphere.emplace(center, radius); return *m_bounding_sphere; diff --git a/engine/src/toast/console/console.cpp b/engine/src/toast/console/console.cpp new file mode 100644 index 000000000..a623b4b3f --- /dev/null +++ b/engine/src/toast/console/console.cpp @@ -0,0 +1,292 @@ +#include "console.hpp" + +#include +#include +#include +#include + +namespace toast::console { +namespace { + +constexpr size_t k_log_lines = 8; +constexpr size_t k_history_lines = 200; + +auto needsSpaceAfter(EntryKind kind) -> bool { + return kind == EntryKind::variable || kind == EntryKind::field || kind == EntryKind::function; +} + +} + +Console::Console() = default; + +Console::~Console() = default; + +auto Console::get() -> Console& { + static Console instance; + return instance; +} + +void Console::attach() { + const std::lock_guard lock(m_mutex); + if (m_attached) { + return; + } + m_attached = true; + m_listener.subscribe( + "console_key", [this](const event::WindowKey& e) { return onKey(e.key, e.action, e.mods); }, 127 + ); + m_listener.subscribe("console_char", [this](const event::WindowChar& e) { return onChar(e.key); }, 127); +} + +void Console::detach() { + const std::lock_guard lock(m_mutex); + if (!m_attached) { + return; + } + m_attached = false; + m_listener.unsubscribe("console_key"); + m_listener.unsubscribe("console_char"); +} + +auto Console::onKey(int key, int action, int mods) -> bool { + const std::lock_guard lock(m_mutex); + + if (action == event::window_input_released) { + return m_held.erase(key) > 0; + } + + if (key == SDLK_F12) { + m_held.insert(key); + if (action == event::window_input_pressed) { + const bool open = !m_open.load(); + m_open = open; + if (open) { + refresh(); + } + } + return true; + } + + if (!m_open.load()) { + return false; + } + m_held.insert(key); + handleKey(key, mods); + return true; +} + +auto Console::onChar(uint32_t codepoint) -> bool { + if (!m_open.load()) { + return false; + } + const std::lock_guard lock(m_mutex); + m_cycling = false; + m_editor.insert(codepoint); + m_history_position = -1; + refresh(); + return true; +} + +void Console::open() { + const std::lock_guard lock(m_mutex); + m_open = true; + refresh(); +} + +void Console::close() { + const std::lock_guard lock(m_mutex); + m_open = false; +} + +auto Console::view() const -> View { + const std::lock_guard lock(m_mutex); + View view {m_open.load(), m_editor.text(), m_editor.cursor(), m_completion, m_selected, m_log}; + view.pins = m_pin_lines; + if (m_has_message) { + view.message_age = std::chrono::duration(std::chrono::steady_clock::now() - m_last_message).count(); + } + return view; +} + +void Console::setNodeRoot(std::function()> root) { + const std::lock_guard lock(m_mutex); + m_model.setNodeRoot(std::move(root)); +} + +void Console::setAssetCheck(std::function check) { + const std::lock_guard lock(m_mutex); + m_model.setAssetCheck(std::move(check)); +} + +void Console::updatePins() { + const auto now = std::chrono::steady_clock::now(); + if (now - m_last_pin_update < std::chrono::milliseconds(100)) { + return; + } + m_last_pin_update = now; + std::vector lines = m_model.pinnedLines(); + const std::lock_guard lock(m_mutex); + m_pin_lines = std::move(lines); +} + +void Console::handleKey(int key, int mods) { + const bool control = (mods & SDL_KMOD_CTRL) != 0; + + if (key != SDLK_TAB && m_cycling) { + m_cycling = false; + refresh(); + } + switch (key) { + case SDLK_RETURN: + case SDLK_KP_ENTER: + execute(); + m_open = false; + return; + case SDLK_ESCAPE: m_open = false; return; + case SDLK_TAB: accept((mods & SDL_KMOD_SHIFT) != 0); return; + case SDLK_UP: + if (m_editor.text().empty() || m_history_position >= 0 || m_completion.entries.empty()) { + navigateHistory(true); + } else { + moveSelection(-1); + } + return; + case SDLK_DOWN: + if (m_editor.text().empty() || m_history_position >= 0 || m_completion.entries.empty()) { + navigateHistory(false); + } else { + moveSelection(1); + } + return; + case SDLK_LEFT: control ? m_editor.wordLeft() : m_editor.left(); break; + case SDLK_RIGHT: control ? m_editor.wordRight() : m_editor.right(); break; + case SDLK_HOME: m_editor.home(); break; + case SDLK_END: m_editor.end(); break; + case SDLK_BACKSPACE: + m_editor.backspace(); + m_history_position = -1; + break; + case SDLK_DELETE: + m_editor.del(); + m_history_position = -1; + break; + case SDLK_V: + if (control) { + if (char* clipboard = SDL_GetClipboardText(); clipboard != nullptr) { + std::string line {clipboard}; + std::ranges::replace(line, '\n', ' '); + std::ranges::replace(line, '\r', ' '); + m_editor.insert(line); + m_history_position = -1; + SDL_free(clipboard); + } + } + break; + default: return; + } + refresh(); +} + +void Console::execute() { + const std::string line = m_editor.text(); + m_editor.set({}); + m_history_position = -1; + m_draft.clear(); + if (line.find_first_not_of(" \t") != std::string::npos) { + if (m_history.empty() || m_history.back() != line) { + m_history.push_back(line); + if (m_history.size() > k_history_lines) { + m_history.erase(m_history.begin()); + } + } + const Result result = m_model.execute(line); + m_pin_lines = m_model.pinnedLines(); + m_log.emplace_back(result.ok, result.message.empty() ? line : result.message); + m_last_message = std::chrono::steady_clock::now(); + m_has_message = true; + if (m_log.size() > k_log_lines) { + m_log.erase(m_log.begin()); + } + } + refresh(); +} + +void Console::applyEntry(const Completion& completion, size_t index, const std::string& text) { + const Entry& entry = completion.entries[index]; + std::string insert = entry.insert; + if (needsSpaceAfter(entry.kind) && (completion.replace_end >= text.size() || text[completion.replace_end] != ' ')) { + insert += ' '; + } + m_editor.set(text); + m_editor.replace(completion.replace_begin, completion.replace_end, insert); +} + +void Console::accept(bool backwards) { + if (!m_cycling) { + const size_t count = m_completion.entries.size(); + if (count == 0 || m_selected >= count) { + return; + } + if (count == 1) { + applyEntry(m_completion, m_selected, m_editor.text()); + m_history_position = -1; + refresh(); + return; + } + m_cycling = true; + m_cycle = m_completion; + m_cycle_text = m_editor.text(); + m_cycle_index = backwards ? (m_selected + count - 1) % count : m_selected; + } else { + const size_t count = m_cycle.entries.size(); + m_cycle_index = backwards ? (m_cycle_index + count - 1) % count : (m_cycle_index + 1) % count; + } + + applyEntry(m_cycle, m_cycle_index, m_cycle_text); + m_completion = m_cycle; + m_selected = m_cycle_index; + m_history_position = -1; +} + +void Console::moveSelection(int step) { + const auto count = static_cast(m_completion.entries.size()); + if (count == 0) { + return; + } + m_selected = static_cast((static_cast(m_selected) + step + count) % count); +} + +void Console::navigateHistory(bool older) { + if (older) { + if (m_history.empty()) { + return; + } + if (m_history_position < 0) { + m_draft = m_editor.text(); + m_history_position = static_cast(m_history.size()) - 1; + } else { + m_history_position = std::max(0, m_history_position - 1); + } + m_editor.set(m_history[static_cast(m_history_position)]); + } else { + if (m_history_position < 0) { + return; + } + if (static_cast(m_history_position) + 1 < m_history.size()) { + ++m_history_position; + m_editor.set(m_history[static_cast(m_history_position)]); + } else { + m_history_position = -1; + m_editor.set(m_draft); + } + } + m_completion = m_model.complete(m_editor.text(), m_editor.cursor()); + m_selected = 0; +} + +void Console::refresh() { + m_completion = m_model.complete(m_editor.text(), m_editor.cursor()); + m_selected = 0; +} + +} diff --git a/engine/src/toast/console/console.hpp b/engine/src/toast/console/console.hpp new file mode 100644 index 000000000..012051787 --- /dev/null +++ b/engine/src/toast/console/console.hpp @@ -0,0 +1,106 @@ +/** + * @file console.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief The F12 console + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::console { + +struct View { + bool open = false; + std::string text; + size_t cursor = 0; + Completion completion; + size_t selected = 0; + std::vector> log; + + double message_age = std::numeric_limits::infinity(); + + std::vector pins; +}; + +class TOAST_API Console { +public: + Console(); + ~Console(); + + Console(const Console&) = delete; + auto operator=(const Console&) -> Console& = delete; + + static auto get() -> Console&; + + void attach(); + void detach(); + + auto onKey(int key, int action, int mods) -> bool; + + auto onChar(uint32_t codepoint) -> bool; + + [[nodiscard]] + auto isOpen() const -> bool { + return m_open.load(std::memory_order_relaxed); + } + + void open(); + void close(); + + void updatePins(); + + [[nodiscard]] + auto view() const -> View; + + void setAssetCheck(std::function check); + + void setNodeRoot(std::function()> root); + +private: + void handleKey(int key, int mods); + void execute(); + void accept(bool backwards); + void applyEntry(const Completion& completion, size_t index, const std::string& text); + void moveSelection(int step); + void navigateHistory(bool older); + void refresh(); + + mutable std::mutex m_mutex; + std::atomic m_open {false}; + LineEditor m_editor; + Model m_model; + Completion m_completion; + size_t m_selected = 0; + std::vector m_history; + int m_history_position = -1; + std::string m_draft; + std::vector> m_log; + std::vector m_pin_lines; + std::chrono::steady_clock::time_point m_last_pin_update; + bool m_cycling = false; + Completion m_cycle; + std::string m_cycle_text; + size_t m_cycle_index = 0; + std::chrono::steady_clock::time_point m_last_message; + bool m_has_message = false; + std::set m_held; + event::Listener m_listener; + bool m_attached = false; +}; + +} diff --git a/engine/src/toast/console/fuzzy.hpp b/engine/src/toast/console/fuzzy.hpp new file mode 100644 index 000000000..6a5294cd1 --- /dev/null +++ b/engine/src/toast/console/fuzzy.hpp @@ -0,0 +1,65 @@ +/** + * @file fuzzy.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief The matching the console's popup narrows its entries with + */ + +#pragma once +#include +#include +#include +#include + +namespace toast::console { + +inline auto fuzzyScore(std::string_view pattern, std::string_view text) -> std::optional { + if (pattern.empty()) { + return 0; + } + + const auto lower = [](char c) { return static_cast(std::tolower(static_cast(c))); }; + const auto word_start = [&](size_t index) { + if (index == 0) { + return true; + } + const char before = text[index - 1]; + return before == '_' || before == '.' || before == '-' || before == ' '; + }; + + int score = 0; + size_t position = 0; + bool first = true; + size_t last = 0; + for (const char wanted : pattern) { + const char target = lower(wanted); + while (position < text.size() && lower(text[position]) != target) { + ++position; + } + if (position >= text.size()) { + return std::nullopt; + } + + score += 10; + if (first) { + if (position == 0) { + score += 40; + } else if (word_start(position)) { + score += 20; + } + score -= static_cast(std::min(position, 10)); + } else if (position == last + 1) { + score += 15; + } else { + score -= static_cast(std::min(position - last - 1, 10)); + score += word_start(position) ? 5 : 0; + } + first = false; + last = position; + ++position; + } + return score; +} + +} diff --git a/engine/src/toast/console/layout.cpp b/engine/src/toast/console/layout.cpp new file mode 100644 index 000000000..83d1d2f37 --- /dev/null +++ b/engine/src/toast/console/layout.cpp @@ -0,0 +1,51 @@ +#include "layout.hpp" + +#include +#include + +namespace toast::console { + +auto layout(const View& view, float width, float height, float line_height, const std::function& measure) + -> Layout { + Layout out; + out.padding = line_height * 0.15F; + + const float bar_height = line_height + (2.0F * out.padding); + out.bar = {0.0F, height - bar_height, width, bar_height}; + out.cursor_x = out.padding + measure("> ") + measure(std::string_view {view.text}.substr(0, view.cursor)); + + const float row_height = line_height; + const size_t entries = view.completion.entries.size(); + const auto fit = static_cast(std::max(0.0F, std::floor(((height * 0.5F) - (2.0F * out.padding)) / row_height))); + const size_t rows = std::min({k_popup_rows, entries, fit}); + float top = out.bar.y; + if (rows > 0) { + const float popup_height = (static_cast(rows) * row_height) + (2.0F * out.padding); + out.popup = {0.0F, out.bar.y - popup_height, std::min(width, 48.0F * line_height), popup_height}; + top = out.popup.y; + + const size_t selected = std::min(view.selected, entries - 1); + const size_t first = selected >= rows ? selected - rows + 1 : 0; + for (size_t i = 0; i < rows; ++i) { + out.rows.push_back({ + first + i, {out.popup.x, out.popup.y + out.padding + (static_cast(i) * row_height), out.popup.w, row_height} + }); + } + } + + const auto room = static_cast(std::max(0.0F, std::floor(height * 0.25F / line_height))); + const size_t shown = std::min(view.log.size(), room); + for (size_t i = 0; i < shown; ++i) { + const size_t line = view.log.size() - shown + i; + const float y = top - (static_cast(shown - i) * line_height); + if (y < 0.0F) { + continue; + } + out.log.push_back({ + line, {0.0F, y, width, line_height} + }); + } + return out; +} + +} diff --git a/engine/src/toast/console/layout.hpp b/engine/src/toast/console/layout.hpp new file mode 100644 index 000000000..a6eae17ad --- /dev/null +++ b/engine/src/toast/console/layout.hpp @@ -0,0 +1,50 @@ +/** + * @file layout.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Where everything the console shows goes + */ + +#pragma once +#include +#include +#include +#include +#include + +namespace toast::console { + +struct Rect { + float x = 0.0F; + float y = 0.0F; + float w = 0.0F; + float h = 0.0F; +}; + +struct RowLayout { + size_t entry = 0; + Rect rect; +}; + +struct LogLayout { + size_t line = 0; + Rect rect; +}; + +struct Layout { + Rect bar; + Rect popup; + std::vector rows; + std::vector log; + float padding = 0.0F; + float cursor_x = 0.0F; +}; + +inline constexpr size_t k_popup_rows = 12; + +TOAST_API auto + layout(const View& view, float width, float height, float line_height, const std::function& measure) + -> Layout; + +} diff --git a/engine/src/toast/console/line_editor.cpp b/engine/src/toast/console/line_editor.cpp new file mode 100644 index 000000000..b4ac8f267 --- /dev/null +++ b/engine/src/toast/console/line_editor.cpp @@ -0,0 +1,153 @@ +#include "line_editor.hpp" + +#include + +namespace toast::console { +namespace { + +auto startsCharacter(char byte) -> bool { + return (static_cast(byte) & 0xC0U) != 0x80U; +} + +auto isSeparator(char c) -> bool { + return c == ' ' || c == '\t' || c == '.'; +} + +auto encode(uint32_t codepoint, std::string& out) -> bool { + if (codepoint < 0x20U || codepoint == 0x7FU || codepoint > 0x10FFFFU || (codepoint >= 0xD800U && codepoint <= 0xDFFFU)) { + return false; + } + if (codepoint < 0x80U) { + out += static_cast(codepoint); + } else if (codepoint < 0x800U) { + out += static_cast(0xC0U | (codepoint >> 6U)); + out += static_cast(0x80U | (codepoint & 0x3FU)); + } else if (codepoint < 0x10000U) { + out += static_cast(0xE0U | (codepoint >> 12U)); + out += static_cast(0x80U | ((codepoint >> 6U) & 0x3FU)); + out += static_cast(0x80U | (codepoint & 0x3FU)); + } else { + out += static_cast(0xF0U | (codepoint >> 18U)); + out += static_cast(0x80U | ((codepoint >> 12U) & 0x3FU)); + out += static_cast(0x80U | ((codepoint >> 6U) & 0x3FU)); + out += static_cast(0x80U | (codepoint & 0x3FU)); + } + return true; +} + +} + +void LineEditor::insert(uint32_t codepoint) { + std::string encoded; + if (encode(codepoint, encoded)) { + m_text.insert(m_cursor, encoded); + m_cursor += encoded.size(); + } +} + +void LineEditor::insert(std::string_view utf8) { + for (size_t i = 0; i < utf8.size();) { + const auto lead = static_cast(utf8[i]); + size_t length = 1; + if (lead >= 0xF0U) { + length = 4; + } else if (lead >= 0xE0U) { + length = 3; + } else if (lead >= 0xC0U) { + length = 2; + } + if (lead < 0x80U) { + insert(static_cast(lead)); + } else if (lead >= 0xC0U && i + length <= utf8.size()) { + uint32_t codepoint = lead & (0xFFU >> (length + 1)); + for (size_t k = 1; k < length; ++k) { + codepoint = (codepoint << 6U) | (static_cast(utf8[i + k]) & 0x3FU); + } + insert(codepoint); + } + i += length; + } +} + +void LineEditor::backspace() { + if (m_cursor == 0) { + return; + } + size_t begin = m_cursor - 1; + while (begin > 0 && !startsCharacter(m_text[begin])) { + --begin; + } + m_text.erase(begin, m_cursor - begin); + m_cursor = begin; +} + +void LineEditor::del() { + if (m_cursor >= m_text.size()) { + return; + } + size_t end = m_cursor + 1; + while (end < m_text.size() && !startsCharacter(m_text[end])) { + ++end; + } + m_text.erase(m_cursor, end - m_cursor); +} + +void LineEditor::left() { + if (m_cursor == 0) { + return; + } + --m_cursor; + while (m_cursor > 0 && !startsCharacter(m_text[m_cursor])) { + --m_cursor; + } +} + +void LineEditor::right() { + if (m_cursor >= m_text.size()) { + return; + } + ++m_cursor; + while (m_cursor < m_text.size() && !startsCharacter(m_text[m_cursor])) { + ++m_cursor; + } +} + +void LineEditor::home() { + m_cursor = 0; +} + +void LineEditor::end() { + m_cursor = m_text.size(); +} + +void LineEditor::wordLeft() { + while (m_cursor > 0 && isSeparator(m_text[m_cursor - 1])) { + --m_cursor; + } + while (m_cursor > 0 && !isSeparator(m_text[m_cursor - 1])) { + --m_cursor; + } +} + +void LineEditor::wordRight() { + while (m_cursor < m_text.size() && isSeparator(m_text[m_cursor])) { + ++m_cursor; + } + while (m_cursor < m_text.size() && !isSeparator(m_text[m_cursor])) { + ++m_cursor; + } +} + +void LineEditor::set(std::string text) { + m_text = std::move(text); + m_cursor = m_text.size(); +} + +void LineEditor::replace(size_t begin, size_t end, std::string_view text) { + end = std::min(end, m_text.size()); + begin = std::min(begin, end); + m_text.replace(begin, end - begin, text); + m_cursor = begin + text.size(); +} + +} diff --git a/engine/src/toast/console/line_editor.hpp b/engine/src/toast/console/line_editor.hpp new file mode 100644 index 000000000..e7db1f18d --- /dev/null +++ b/engine/src/toast/console/line_editor.hpp @@ -0,0 +1,53 @@ +/** + * @file line_editor.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief The text of the console's one line and the + */ + +#pragma once +#include +#include +#include +#include + +namespace toast::console { + +class TOAST_API LineEditor { +public: + void insert(uint32_t codepoint); + + void insert(std::string_view utf8); + + void backspace(); + void del(); + void left(); + void right(); + void home(); + void end(); + + void wordLeft(); + + void wordRight(); + + void set(std::string text); + + void replace(size_t begin, size_t end, std::string_view text); + + [[nodiscard]] + auto text() const -> const std::string& { + return m_text; + } + + [[nodiscard]] + auto cursor() const -> size_t { + return m_cursor; + } + +private: + std::string m_text; + size_t m_cursor = 0; +}; + +} diff --git a/engine/src/toast/console/model.cpp b/engine/src/toast/console/model.cpp new file mode 100644 index 000000000..f24d0e6cc --- /dev/null +++ b/engine/src/toast/console/model.cpp @@ -0,0 +1,485 @@ +#include "model.hpp" + +#include "fuzzy.hpp" +#include "node_command.hpp" +#include "ranking.hpp" +#include "relative.hpp" + +#include +#include +#include +#include +#include +#include + +namespace toast::console { +namespace { + +using namespace toast::params; + +constexpr std::string_view k_whitespace = " \t"; + +auto trim(std::string_view text) -> std::string_view { + const size_t first = text.find_first_not_of(k_whitespace); + if (first == std::string_view::npos) { + return {}; + } + return text.substr(first, text.find_last_not_of(k_whitespace) - first + 1); +} + +auto currentText(const ParamBase& param) -> std::string { + const std::string path = std::string {param.group()->name()} + "." + std::string {param.id()}; + auto value = Registry::get().pendingValue(path); + return toText(value ? *value : param.snapshot(), param.type(), param.options()); +} + +auto pathOf(const ParamBase& param) -> std::string { + return std::string {param.group()->name()} + "." + std::string {param.id()}; +} + +auto editDistance(std::string_view a, std::string_view b) -> size_t { + std::vector previous(b.size() + 1); + std::vector current(b.size() + 1); + for (size_t j = 0; j <= b.size(); ++j) { + previous[j] = j; + } + for (size_t i = 1; i <= a.size(); ++i) { + current[0] = i; + for (size_t j = 1; j <= b.size(); ++j) { + const size_t substitute = previous[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1); + current[j] = std::min({previous[j] + 1, current[j - 1] + 1, substitute}); + } + std::swap(previous, current); + } + return previous[b.size()]; +} + +auto closeMatches(std::string_view typed) -> std::vector { + struct Candidate { + std::string path; + size_t distance; + }; + + std::vector candidates; + const size_t allowed = std::max(2, typed.size() / 5); + for (const GroupBase* group : Registry::get().groups()) { + for (const ParamBase* param : group->params()) { + std::string path = pathOf(*param); + const size_t distance = editDistance(typed, path); + if (distance <= allowed) { + candidates.push_back({std::move(path), distance}); + } + } + } + std::ranges::sort(candidates, [](const Candidate& a, const Candidate& b) { + return a.distance != b.distance ? a.distance < b.distance : a.path < b.path; + }); + std::vector out; + for (size_t i = 0; i < candidates.size() && i < 3; ++i) { + out.push_back(std::move(candidates[i].path)); + } + return out; +} + +auto joinWithOr(const std::vector& items) -> std::string { + std::string out; + for (size_t i = 0; i < items.size(); ++i) { + if (i > 0) { + out += i + 1 == items.size() ? " or " : ", "; + } + out += items[i]; + } + return out; +} + +auto valueNames(const ParamBase& param) -> std::vector { + std::vector names; + if (param.isArray()) { + return names; + } + if (param.type() == Type::boolean) { + return {"true", "false"}; + } + if (param.type() == Type::integer) { + for (const auto option : param.options()) { + names.emplace_back(option); + } + } + return names; +} + +auto completeSet(std::string_view line, size_t cursor) -> Completion { + cursor = std::min(cursor, line.size()); + Completion completion; + + const size_t word_begin = std::min(line.find_first_not_of(k_whitespace), line.size()); + size_t word_end = line.find_first_of(k_whitespace, word_begin); + if (word_end == std::string_view::npos) { + word_end = line.size(); + } + + if (cursor > word_end) { + const ParamBase* param = Registry::get().find(line.substr(word_begin, word_end - word_begin)); + if (param == nullptr) { + return completion; + } + completion.hint = currentText(*param); + const size_t argument_begin = std::min(line.find_first_not_of(k_whitespace, word_end), line.size()); + const size_t partial_end = std::max(cursor, argument_begin); + const std::string_view partial = line.substr(argument_begin, partial_end - argument_begin); + completion.replace_begin = partial_end == cursor && argument_begin > cursor ? cursor : argument_begin; + completion.replace_end = partial_end; + + std::vector scored; + for (const auto& name : valueNames(*param)) { + if (const auto score = fuzzyScore(partial, name)) { + scored.push_back({ + {name, name, {}, EntryKind::value}, + *score + }); + } + } + if (!partial.empty()) { + rank(scored); + } + for (auto& item : scored) { + completion.entries.push_back(std::move(item.entry)); + } + return completion; + } + + const std::string_view typed = line.substr(word_begin, cursor - word_begin); + const size_t last_dot = typed.rfind('.'); + const std::string_view scope = last_dot == std::string_view::npos ? std::string_view {} : typed.substr(0, last_dot); + const std::string_view partial = last_dot == std::string_view::npos ? typed : typed.substr(last_dot + 1); + completion.replace_begin = word_begin + (last_dot == std::string_view::npos ? 0 : last_dot + 1); + completion.replace_end = word_end; + + if (last_dot == std::string_view::npos) { + std::vector groups; + for (const GroupBase* group : Registry::get().groups()) { + const std::string name {group->name()}; + if (const auto score = fuzzyScore(partial, name)) { + groups.push_back({ + {name, name + ".", {}, EntryKind::group}, + *score + }); + } + } + append(completion.entries, groups); + return completion; + } + + const size_t group_dot = scope.find('.'); + const GroupBase* group = Registry::get().findGroup(scope.substr(0, group_dot)); + if (group == nullptr) { + return completion; + } + const std::string inside = + group_dot == std::string_view::npos ? std::string {} : std::string {scope.substr(group_dot + 1)} + "."; + + std::vector variables; + std::vector subgroups; + std::unordered_set seen; + for (const ParamBase* param : group->params()) { + const std::string_view id = param->id(); + if (!id.starts_with(inside)) { + continue; + } + const std::string_view rest = id.substr(inside.size()); + const size_t dot = rest.find('.'); + if (dot == std::string_view::npos) { + if (const auto score = fuzzyScore(partial, rest)) { + variables.push_back({ + {std::string {rest}, std::string {rest}, currentText(*param), EntryKind::variable}, + *score + }); + } + } else { + const std::string name {rest.substr(0, dot)}; + if (const auto score = fuzzyScore(partial, name); score && seen.insert(name).second) { + subgroups.push_back({ + {name, name + ".", {}, EntryKind::subgroup}, + *score + }); + } + } + } + append(completion.entries, variables); + append(completion.entries, subgroups); + return completion; +} + +} + +auto Model::complete(std::string_view line, size_t cursor) const -> Completion { + cursor = std::min(cursor, line.size()); + Completion completion; + + const size_t first = std::min(line.find_first_not_of(k_whitespace), line.size()); + size_t first_end = line.find_first_of(k_whitespace, first); + if (first_end == std::string_view::npos) { + first_end = line.size(); + } + + // the first word is the command + if (cursor <= first_end) { + const std::string_view typed = line.substr(first, cursor - first); + completion.replace_begin = first; + completion.replace_end = first_end; + std::vector commands; + for (const std::string_view name : {"set", "node", "show", "hide", "restore"}) { + if (const auto score = fuzzyScore(typed, name)) { + commands.push_back({ + {std::string {name}, name == "restore" ? std::string {name} : std::string {name} + " ", {}, EntryKind::command}, + *score + }); + } + } + append(completion.entries, commands); + return completion; + } + + const std::string_view command = line.substr(first, first_end - first); + if (command == "node" || command == "show" || command == "pin") { + return completeNode(m_node_root, line, cursor, first_end); + } + if (command == "hide" || command == "unpin") { + return completeHide(line, cursor, first_end); + } + if (command == "set") { + completion = completeSet(line.substr(first_end), cursor - first_end); + completion.replace_begin += first_end; + completion.replace_end += first_end; + } + return completion; +} + +auto Model::execute(std::string_view raw) -> Result { + const std::string_view line = trim(raw); + if (line.empty()) { + return {true, {}}; + } + + const size_t command_end = line.find_first_of(k_whitespace); + const std::string_view command = line.substr(0, command_end); + const std::string_view arguments = command_end == std::string_view::npos ? std::string_view {} : trim(line.substr(command_end)); + + auto& registry = Registry::get(); + if (command == "restore" && arguments.empty()) { + registry.requestRestore(); + return {true, "restoring everything from disk"}; + } + if (command == "node") { + return executeNode(m_node_root, arguments); + } + if (command == "show" || command == "pin") { + return pin(arguments); + } + if (command == "hide" || command == "unpin") { + return hide(arguments); + } + if (command != "set") { + if (registry.find(command) != nullptr) { + return {false, std::format("did you mean 'set {}'?", line)}; + } + return {false, std::format("no command '{}'; there are set, node, show, hide and restore", command)}; + } + if (arguments.empty()) { + return {false, "usage: set [value]"}; + } + + const size_t path_end = arguments.find_first_of(k_whitespace); + const std::string_view path = arguments.substr(0, path_end); + const std::string_view value_text = path_end == std::string_view::npos ? std::string_view {} : trim(arguments.substr(path_end)); + + ParamBase* param = registry.find(path); + if (param == nullptr && path.starts_with("render.")) { + // `render.view_mode` for `renderer.view_mode` + param = registry.find("renderer." + std::string {path.substr(7)}); + } + if (param == nullptr) { + std::string message = std::format("no parameter '{}'", path); + if (const auto close = closeMatches(path); !close.empty()) { + message += std::format(", did you mean {}?", joinWithOr(close)); + } else if (!path.contains('.')) { + message = std::format("no group '{}'", path); + } + return {false, std::move(message)}; + } + + if (value_text.empty()) { + return {true, std::format("{} = {}", path, currentText(*param))}; + } + + std::string resolved; + std::string_view text = value_text; + if (hasRelative(text)) { + if (param->isArray()) { + return {false, std::format("{}: a list cannot be written relative to itself", path)}; + } + auto worked_out = resolveRelative(text, currentText(*param), param->type()); + if (!worked_out) { + return {false, std::format("{}: {}", path, worked_out.error())}; + } + resolved = std::move(*worked_out); + text = resolved; + } + + auto value = fromText(text, param->type(), param->isArray(), param->options()); + if (!value) { + return {false, std::format("{}: {}", path, value.error())}; + } + + if (param->type() == Type::asset && m_asset_check) { + const auto check = [&](const Scalar& scalar) { + const auto* asset = std::get_if(&scalar); + return asset == nullptr || asset->uri.empty() || m_asset_check(asset->uri); + }; + const auto missing = [&]() -> std::string { + if (const auto* scalar = std::get_if(&*value)) { + return check(*scalar) ? std::string {} : std::get(*scalar).uri; + } + for (const auto& item : std::get>(*value)) { + if (!check(item)) { + return std::get(item).uri; + } + } + return {}; + }(); + if (!missing.empty()) { + return {false, std::format("{}: no asset '{}'", path, missing)}; + } + } + + if (!param->accepts(*value)) { + return {false, std::format("{}: that is not a value it can take", path)}; + } + const std::string shown = toText(*value, param->type(), param->options()); + registry.request(pathOf(*param), std::move(*value), Layer::runtime); + return {true, std::format("{} = {}", path, shown)}; +} + +namespace { + +auto lowered(std::string_view text) -> std::string { + std::string out {text}; + std::ranges::transform(out, out.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + return out; +} + +} + +auto Model::describe(const Pin& pin) const -> std::pair { + if (pin.parameter) { + const ParamBase* param = Registry::get().find(pin.spec); + return {pin.spec, param != nullptr ? currentText(*param) : std::string {"?"}}; + } + const Result described = describeNode(m_node_root, pin.spec); + if (!described.ok) { + return {pin.spec, std::format("({})", described.message)}; + } + const size_t split = described.message.find(" = "); + if (split == std::string::npos) { + return {pin.spec, described.message}; + } + return {described.message.substr(0, split), described.message.substr(split + 3)}; +} + +auto Model::pinnedLines() const -> std::vector { + std::vector lines; + lines.reserve(m_pins.size()); + for (const Pin& pin : m_pins) { + const auto [label, value] = describe(pin); + lines.push_back(std::format("{} = {}", label, value)); + } + return lines; +} + +auto Model::pin(std::string_view spec) -> Result { + spec = trim(spec); + if (spec.empty()) { + return {false, "usage: show . or show "}; + } + const std::string wanted = lowered(spec); + if (std::ranges::any_of(m_pins, [&](const Pin& pin) { return lowered(pin.spec) == wanted; })) { + return {false, std::format("{} is already shown", spec)}; + } + if (Registry::get().find(spec) != nullptr) { + m_pins.push_back({std::string {spec}, true}); + return {true, std::format("showing {}", spec)}; + } + Result described = describeNode(m_node_root, spec); + if (!described.ok) { + return described; + } + m_pins.push_back({std::string {spec}, false}); + return {true, std::format("showing {}", spec)}; +} + +auto Model::hide(std::string_view spec) -> Result { + spec = trim(spec); + if (spec.empty()) { + if (m_pins.empty()) { + return {true, "nothing is shown"}; + } + std::string list; + for (const Pin& pin : m_pins) { + list += list.empty() ? "" : ", "; + list += pin.spec; + } + return {true, std::format("shown: {}", list)}; + } + if (spec == "all" || spec == "*") { + m_pins.clear(); + return {true, "nothing is shown any more"}; + } + const std::string wanted = lowered(spec); + const auto at = std::ranges::find_if(m_pins, [&](const Pin& pin) { return lowered(pin.spec) == wanted; }); + if (at == m_pins.end()) { + return {false, std::format("{} is not shown", spec)}; + } + const std::string name = at->spec; + m_pins.erase(at); + return {true, std::format("hid {}", name)}; +} + +auto Model::completeHide(std::string_view line, size_t cursor, size_t base) const -> Completion { + Completion completion; + const size_t begin = std::min(line.find_first_not_of(k_whitespace, std::min(base, line.size())), line.size()); + cursor = std::clamp(cursor, begin, line.size()); + const std::string_view partial = line.substr(begin, cursor - begin); + completion.replace_begin = begin; + completion.replace_end = line.size(); + + std::vector scored; + for (const Pin& pin : m_pins) { + if (const auto score = fuzzyScore(partial, pin.spec)) { + scored.push_back({ + {pin.spec, pin.spec, describe(pin).second, EntryKind::field}, + *score + }); + } + } + if (!partial.empty()) { + rank(scored); + } + for (auto& item : scored) { + completion.entries.push_back(std::move(item.entry)); + } + return completion; +} + +void Model::setNodeRoot(std::function()> root) { + m_node_root = std::move(root); +} + +void Model::applyQueued() { + runQueuedNodeWork(); +} + +void Model::setAssetCheck(std::function check) { + m_asset_check = std::move(check); +} + +} diff --git a/engine/src/toast/console/model.hpp b/engine/src/toast/console/model.hpp new file mode 100644 index 000000000..8159d3cb0 --- /dev/null +++ b/engine/src/toast/console/model.hpp @@ -0,0 +1,89 @@ +/** + * @file model.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief What the console knows about a line + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace toast { +class Node; +} + +namespace toast::console { + +enum class EntryKind : uint8_t { + group, + subgroup, + variable, + value, + command, + node, + field, + function +}; + +struct Entry { + std::string label; + std::string insert; + std::string value; + EntryKind kind = EntryKind::variable; +}; + +struct Completion { + std::vector entries; + size_t replace_begin = 0; + size_t replace_end = 0; + + std::string hint; +}; + +struct Result { + bool ok = true; + std::string message; +}; + +class TOAST_API Model { +public: + [[nodiscard]] + auto complete(std::string_view line, size_t cursor) const -> Completion; + + auto execute(std::string_view raw) -> Result; + + void setNodeRoot(std::function()> root); + + [[nodiscard]] + auto pinnedLines() const -> std::vector; + + static void applyQueued(); + + void setAssetCheck(std::function check); + +private: + struct Pin { + std::string spec; + bool parameter = false; + }; + + auto pin(std::string_view spec) -> Result; + auto hide(std::string_view spec) -> Result; + [[nodiscard]] + auto completeHide(std::string_view line, size_t cursor, size_t base) const -> Completion; + [[nodiscard]] + auto describe(const Pin& pin) const -> std::pair; + + std::function m_asset_check; + std::function()> m_node_root; + std::vector m_pins; +}; + +} diff --git a/engine/src/toast/console/node_command.cpp b/engine/src/toast/console/node_command.cpp new file mode 100644 index 000000000..00c27f1ab --- /dev/null +++ b/engine/src/toast/console/node_command.cpp @@ -0,0 +1,1473 @@ +#include "node_command.hpp" + +#include "fuzzy.hpp" +#include "ranking.hpp" +#include "relative.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::console { +namespace { + +using namespace toast::params; + +constexpr std::string_view k_whitespace = " \t"; +constexpr std::string_view k_usage = "usage: node . [value] or node . [arg;arg;...]"; + +std::mutex g_queue_mutex; +std::vector> g_queue; + +void enqueue(std::function work) { + const std::lock_guard lock(g_queue_mutex); + g_queue.push_back(std::move(work)); +} + +auto trim(std::string_view text) -> std::string_view { + const size_t first = text.find_first_not_of(k_whitespace); + if (first == std::string_view::npos) { + return {}; + } + return text.substr(first, text.find_last_not_of(k_whitespace) - first + 1); +} + +auto typed(std::string_view name) -> std::string { + std::string out {name}; + std::ranges::replace(out, ' ', '_'); + return out; +} + +auto lowerCase(char c) -> char { + return static_cast(std::tolower(static_cast(c))); +} + +auto sameText(std::string_view a, std::string_view b) -> bool { + return std::ranges::equal(a, b, [](char x, char y) { return lowerCase(x) == lowerCase(y); }); +} + +auto sameName(std::string_view node_name, std::string_view segment) -> bool { + if (node_name.size() != segment.size()) { + return false; + } + for (size_t i = 0; i < node_name.size(); ++i) { + const char a = node_name[i] == ' ' ? '_' : node_name[i]; + if (lowerCase(a) != lowerCase(segment[i])) { + return false; + } + } + return true; +} + +auto typeName(const Node& node) -> std::string { + if (node.info() == nullptr) { + return "Node"; + } + std::string_view type = node.info()->type; + if (type.starts_with("toast::")) { + type.remove_prefix(7); + } + return std::string {type}; +} + +auto cleanType(std::string_view type) -> std::string { + std::string out {type}; + for (const std::string_view junk : {"const ", "toast::", "std::", "glm::"}) { + for (size_t at = out.find(junk); at != std::string::npos; at = out.find(junk)) { + out.erase(at, junk.size()); + } + } + std::erase(out, '&'); + return std::string {trim(out)}; +} + +auto splitArguments(std::string_view text) -> std::vector { + std::vector out; + if (trim(text).empty()) { + return out; + } + size_t begin = 0; + bool quoted = false; + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] == '\\' && quoted) { + ++i; + } else if (text[i] == '"') { + quoted = !quoted; + } else if (text[i] == ';' && !quoted) { + out.push_back(trim(text.substr(begin, i - begin))); + begin = i + 1; + } + } + out.push_back(trim(text.substr(begin))); + return out; +} + +auto countWords(std::string_view text) -> size_t { + size_t words = 0; + bool inside = false; + for (const char c : text) { + const bool space = c == ' ' || c == '\t'; + if (!space && !inside) { + ++words; + } + inside = !space; + } + return words; +} + +struct Found { + Box node; + std::string error; +}; + +void collect(const Node& node, std::string_view name, std::vector>& out) { + if (sameName(node.name(), name)) { + out.push_back(node.box()); + } + for (const auto& child : node.children()) { + collect(*child, name, out); + } +} + +auto resolve(const Box& root, std::string_view path) -> Found { + if (!root.exists()) { + return {{}, "there is no world root to look in"}; + } + const TreeReadLock lock(*root); + + Box current; + std::string walked; + size_t start = 0; + while (true) { + const size_t slash = path.find('/', start); + const std::string_view segment = path.substr(start, slash == std::string_view::npos ? std::string_view::npos : slash - start); + if (segment.empty()) { + return {{}, std::format("'{}' has an empty name in it", path)}; + } + + std::vector> matches; + if (start == 0 && sameText(segment, "global")) { + if (slash == std::string_view::npos) { + return {{}, "global/ is followed by the name of a node, wherever it is"}; + } + start = slash + 1; + const size_t next = path.find('/', start); + const std::string_view name = path.substr(start, next == std::string_view::npos ? std::string_view::npos : next - start); + if (name.empty()) { + return {{}, std::format("'{}' has an empty name in it", path)}; + } + collect(*root, name, matches); + if (matches.empty()) { + return {{}, std::format("no node called '{}' anywhere", name)}; + } + if (matches.size() > 1) { + return {{}, std::format("{} nodes are called '{}'; start from one of their parents", matches.size(), name)}; + } + current = matches.front(); + walked = "global/" + std::string {name}; + if (next == std::string_view::npos) { + return {current, {}}; + } + start = next + 1; + continue; + } + if (start == 0) { + if (sameText(segment, "world")) { + matches.push_back(root); + } else { + for (const auto& child : root->children()) { + if (sameName(child->name(), segment)) { + matches.push_back(child); + } + } + } + } else { + for (const auto& child : current->children()) { + if (sameName(child->name(), segment)) { + matches.push_back(child); + } + } + } + + if (matches.empty()) { + if (start == 0) { + return {{}, std::format("no node called '{}' on the root; global/{} looks everywhere", segment, segment)}; + } + return {{}, std::format("'{}' has no child called '{}'", walked, segment)}; + } + if (matches.size() > 1) { + return { + {}, + std::format("'{}' has {} children called '{}'", walked.empty() ? std::string {"world"} : walked, matches.size(), segment) + }; + } + current = matches.front(); + walked += walked.empty() ? std::string {segment} : "/" + std::string {segment}; + + if (slash == std::string_view::npos) { + return {current, {}}; + } + start = slash + 1; + } +} + +auto scalarOf(const std::any& value) -> std::optional> { + const auto integer = [](auto v) { return std::pair {Scalar {static_cast(v)}, Type::integer}; }; + + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {*v}, Type::boolean}; + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return integer(*v); + } + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {static_cast(*v)}, Type::floating}; + } + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {*v}, Type::floating}; + } + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {*v}, Type::string}; + } + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {*v}, Type::vec2}; + } + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {*v}, Type::vec3}; + } + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {*v}, Type::vec4}; + } + if (const auto* v = std::any_cast(&value)) { + return std::pair {Scalar {*v}, Type::quat}; + } + return std::nullopt; +} + +auto anyText(const std::any& value) -> std::string { + if (const auto* uid = std::any_cast(&value)) { + return uid->data() == 0 ? "none" : assets::AssetManager::getURI(*uid); + } + if (const auto scalar = scalarOf(value)) { + return toText(Value {scalar->first}, scalar->second); + } + if (const auto* box = std::any_cast>(&value)) { + return box->exists() ? typed((*box)->name()) : "none"; + } + return {}; +} + +auto fieldText(Node& node, const FieldInfo& field) -> std::string { + if (field.is_array) { + return "(list)"; + } + if (field.get == nullptr) { + return {}; + } + return anyText(field.get(&node)); +} + +auto scalarFrom(std::string_view text, Type type) -> std::expected { + auto value = fromText(text, type, false); + if (!value) { + return std::unexpected(value.error()); + } + return std::get(*value); +} + +template +auto clampedInteger(int64_t value) -> Int { + const auto lowest = static_cast(std::numeric_limits::min()); + const int64_t highest = std::in_range(std::numeric_limits::max()) + ? static_cast(std::numeric_limits::max()) + : std::numeric_limits::max(); + return static_cast(std::clamp(value, lowest, highest)); +} + +auto quatFrom(std::string_view text) -> std::expected { + if (countWords(text) == 3) { + auto angles = scalarFrom(text, Type::vec3); + if (!angles) { + return std::unexpected(angles.error()); + } + return glm::quat {glm::radians(std::get(*angles))}; + } + auto value = scalarFrom(text, Type::quat); + if (!value) { + return std::unexpected(value.error()); + } + return std::get(*value); +} + +using Setter = std::function; + +auto fieldSetter(const FieldInfo& field, std::string_view text) -> std::expected { + if (field.is_array) { + return std::unexpected("it is a list, which cannot be typed here"); + } + const std::string name {field.name}; + + const auto make = [&](Type type, auto&& convert) -> std::expected { + auto scalar = scalarFrom(text, type); + if (!scalar) { + return std::unexpected(scalar.error()); + } + return convert(*scalar); + }; + + switch (field.value_type) { + case FieldType::bool_t: + return make(Type::boolean, [&](const Scalar& s) -> Setter { + return [name, v = std::get(s)](Node& n) { n.set(name, v); }; + }); + case FieldType::int_t: + return make(Type::integer, [&](const Scalar& s) -> Setter { + return [name, v = clampedInteger(std::get(s))](Node& n) { n.set(name, v); }; + }); + case FieldType::float_t: + return make(Type::floating, [&](const Scalar& s) -> Setter { + return [name, v = static_cast(std::get(s))](Node& n) { n.set(name, v); }; + }); + case FieldType::double_t: + return make(Type::floating, [&](const Scalar& s) -> Setter { + return [name, v = std::get(s)](Node& n) { n.set(name, v); }; + }); + case FieldType::string_t: + return make(Type::string, [&](const Scalar& s) -> Setter { + return [name, v = std::get(s)](Node& n) { n.set(name, v); }; + }); + case FieldType::vec2_t: + return make(Type::vec2, [&](const Scalar& s) -> Setter { + return [name, v = std::get(s)](Node& n) { n.set(name, v); }; + }); + case FieldType::vec3_t: + return make(Type::vec3, [&](const Scalar& s) -> Setter { + return [name, v = std::get(s)](Node& n) { n.set(name, v); }; + }); + case FieldType::vec4_t: + return make(Type::vec4, [&](const Scalar& s) -> Setter { + return [name, v = std::get(s)](Node& n) { n.set(name, v); }; + }); + case FieldType::quaternion_t: { + auto rotation = quatFrom(text); + if (!rotation) { + return std::unexpected(rotation.error()); + } + return Setter {[name, v = *rotation](Node& n) { n.set(name, v); }}; + } + default: return std::unexpected("it cannot be typed here"); + } +} + +struct Argument { + std::any value; + std::string text; + bool view = false; +}; + +auto isWholeNumber(std::string_view text) -> bool { + int64_t ignored = 0; + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), ignored); + return error == std::errc {} && end == text.data() + text.size(); +} + +auto isNumber(std::string_view text) -> bool { + double ignored = 0; + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), ignored); + return error == std::errc {} && end == text.data() + text.size(); +} + +auto guessArgument(std::string_view text) -> std::any { + if (text == "true" || text == "false") { + return text == "true"; + } + if (isWholeNumber(text)) { + int64_t number = 0; + std::from_chars(text.data(), text.data() + text.size(), number); + return clampedInteger(number); + } + if (isNumber(text)) { + double number = 0; + std::from_chars(text.data(), text.data() + text.size(), number); + return number; + } + if (const size_t words = countWords(text); words >= 2 && words <= 4 && text.front() != '"') { + Type type = Type::vec4; + if (words == 2) { + type = Type::vec2; + } else if (words == 3) { + type = Type::vec3; + } + const auto vector = scalarFrom(text, type); + if (vector) { + if (const auto* v = std::get_if(&*vector)) { + return *v; + } + if (const auto* v = std::get_if(&*vector)) { + return *v; + } + return std::get(*vector); + } + } + if (auto string = scalarFrom(text, Type::string)) { + return std::get(*string); + } + return std::string {text}; +} + +struct HandleKind { + const std::type_info* id; + std::string_view asset_type; + std::function make; +}; + +template +auto handleKind(std::string_view asset_type) -> HandleKind { + return {&typeid(assets::Handle), asset_type, [](assets::Asset* asset, toast::UID uid, std::string_view uri) -> std::any { + return assets::Handle(asset, uid, uri); + }}; +} + +auto handleKinds() -> const std::vector& { + static const std::vector kinds { + handleKind("mesh"), + handleKind("texture"), + handleKind("material"), + handleKind("material_instance"), + handleKind("animation"), + handleKind("skeleton"), + handleKind("node"), + handleKind("curve"), + handleKind("data"), + handleKind("script"), + handleKind("shader"), + }; + return kinds; +} + +auto handleKindOf(const std::type_info* id) -> const HandleKind* { + if (id == nullptr) { + return nullptr; + } + const auto at = std::ranges::find_if(handleKinds(), [&](const HandleKind& kind) { return *kind.id == *id; }); + return at == handleKinds().end() ? nullptr : &*at; +} + +auto assetTypeOfSpelling(std::string_view spelling) -> std::string { + const size_t open = spelling.find("Handle<"); + const size_t close = spelling.rfind('>'); + if (open == std::string_view::npos || close == std::string_view::npos || close <= open) { + return {}; + } + std::string_view name = spelling.substr(open + 7, close - open - 7); + if (const size_t colon = name.rfind(':'); colon != std::string_view::npos) { + name = name.substr(colon + 1); + } + if (name == "Prefab") { + return "node"; + } + std::string out; + for (const char c : name) { + if (std::isupper(static_cast(c)) != 0 && !out.empty()) { + out += '_'; + } + out += static_cast(std::tolower(static_cast(c))); + } + return out; +} + +auto pathText(std::string_view text) -> std::expected { + text = trim(text); + if (text.starts_with('"')) { + auto quoted = scalarFrom(text, Type::string); + if (!quoted) { + return std::unexpected(quoted.error()); + } + return std::get(*quoted); + } + return std::string {text}; +} + +auto assetByPath(std::string_view text, std::string_view asset_type) -> std::expected { + const auto path = pathText(text); + if (!path) { + return std::unexpected(path.error()); + } + if (path->empty() || *path == "none") { + return toast::UID {}; + } + if (!assets::AssetManager::isInitialized()) { + return std::unexpected("there are no assets to look in"); + } + const auto uid = assets::AssetManager::resolveURI(*path); + if (!uid) { + return std::unexpected(std::format("no asset '{}'", *path)); + } + if (const std::string actual = assets::AssetManager::typeOf(*uid); + !asset_type.empty() && !actual.empty() && actual != asset_type) { + return std::unexpected(std::format("'{}' is a {}, and this takes a {}", *path, actual, asset_type)); + } + return *uid; +} + +auto parseArgument(const ParameterInfo& parameter, std::string_view text, const NodeRoot& root) + -> std::expected { + const std::type_info& type = parameter.type_id != nullptr ? *parameter.type_id : typeid(void); + Argument argument; + argument.text = std::string {text}; + + const auto fail = [&](const std::string& message) -> std::expected { + return std::unexpected(std::format("{}: {}", parameter.name, message)); + }; + + if (type == typeid(bool)) { + auto v = scalarFrom(text, Type::boolean); + if (!v) { + return fail(v.error()); + } + argument.value = std::get(*v); + return argument; + } + if (type == typeid(int) || type == typeid(unsigned int) || type == typeid(int64_t) || type == typeid(uint64_t) || + type == typeid(uint8_t) || type == typeid(int16_t) || type == typeid(uint16_t)) { + auto v = scalarFrom(text, Type::integer); + if (!v) { + return fail(v.error()); + } + const int64_t n = std::get(*v); + if (type == typeid(int)) { + argument.value = clampedInteger(n); + } else if (type == typeid(unsigned int)) { + argument.value = clampedInteger(n); + } else if (type == typeid(int64_t)) { + argument.value = n; + } else if (type == typeid(uint64_t)) { + argument.value = static_cast(std::max(n, 0)); + } else if (type == typeid(uint8_t)) { + argument.value = clampedInteger(n); + } else if (type == typeid(int16_t)) { + argument.value = clampedInteger(n); + } else { + argument.value = clampedInteger(n); + } + return argument; + } + if (type == typeid(float) || type == typeid(double)) { + auto v = scalarFrom(text, Type::floating); + if (!v) { + return fail(v.error()); + } + if (type == typeid(float)) { + argument.value = static_cast(std::get(*v)); + } else { + argument.value = std::get(*v); + } + return argument; + } + if (type == typeid(std::string) || type == typeid(std::string_view)) { + auto v = scalarFrom(text, Type::string); + if (!v) { + return fail(v.error()); + } + argument.text = std::get(*v); + argument.view = type == typeid(std::string_view); + argument.value = argument.text; + return argument; + } + if (type == typeid(glm::vec2) || type == typeid(glm::vec3) || type == typeid(glm::vec4)) { + Type wanted = Type::vec4; + if (type == typeid(glm::vec2)) { + wanted = Type::vec2; + } else if (type == typeid(glm::vec3)) { + wanted = Type::vec3; + } + auto v = scalarFrom(text, wanted); + if (!v) { + return fail(v.error()); + } + if (const auto* a = std::get_if(&*v)) { + argument.value = *a; + } else if (const auto* b = std::get_if(&*v)) { + argument.value = *b; + } else { + argument.value = std::get(*v); + } + return argument; + } + if (type == typeid(glm::quat)) { + auto v = quatFrom(text); + if (!v) { + return fail(v.error()); + } + argument.value = *v; + return argument; + } + if (const HandleKind* kind = handleKindOf(parameter.type_id)) { + const auto uid = assetByPath(text, kind->asset_type); + if (!uid) { + return fail(uid.error()); + } + assets::Asset* asset = uid->data() != 0 ? assets::AssetManager::get().load(*uid) : nullptr; + argument.value = kind->make(asset, *uid, uid->data() != 0 ? assets::AssetManager::getURI(*uid) : std::string {}); + return argument; + } + if (type == typeid(Box)) { + auto found = resolve(root ? root() : Box {}, text); + if (!found.node.exists()) { + return fail(found.error); + } + argument.value = found.node; + return argument; + } + return fail(std::format("a {} cannot be typed here", cleanType(parameter.type))); +} + +auto parametersText(const FunctionInfo& function) -> std::string { + std::string out; + for (const auto& parameter : function.parameters) { + out += out.empty() ? "" : "; "; + out += std::format("{} {}", cleanType(parameter.type), parameter.name); + if (parameter.default_value) { + out += std::format(" = {}", *parameter.default_value); + } + } + return out; +} + +enum class MemberKind : uint8_t { + field, + enabled, + function, + lua_variable, + lua_function +}; + +struct Member { + MemberKind kind = MemberKind::field; + std::string name; + std::string detail; + const FieldInfo* field = nullptr; + const FunctionInfo* function = nullptr; + std::optional variable; +}; + +auto luaKindName(scripting::LuaVarKind kind) -> std::string { + using scripting::LuaVarKind; + switch (kind) { + case LuaVarKind::boolean: return "bool"; + case LuaVarKind::integer: return "int"; + case LuaVarKind::number: return "number"; + case LuaVarKind::string: return "string"; + case LuaVarKind::vec2: return "vec2"; + case LuaVarKind::vec3: return "vec3"; + case LuaVarKind::vec4: return "vec4"; + case LuaVarKind::color3: return "color3"; + case LuaVarKind::color4: return "color4"; + case LuaVarKind::node_ref: return "node"; + case LuaVarKind::asset_ref: return "asset"; + } + return {}; +} + +auto findMember(std::vector& all, std::string_view name) -> std::optional { + for (auto& candidate : all) { + if (candidate.name == name) { + return candidate; + } + } + const Member* found = nullptr; + for (const auto& candidate : all) { + if (sameText(candidate.name, name)) { + if (found != nullptr) { + return std::nullopt; + } + found = &candidate; + } + } + return found != nullptr ? std::optional {*found} : std::nullopt; +} + +auto membersOf(Node& node) -> std::vector { + std::vector out; + std::set> seen; + + for (const NodeInfo* info = node.info(); info != nullptr; info = info->base_type) { + for (const auto& field : info->all_fields) { + if (field.hasAttribute("Hidden") || !seen.insert(std::string {field.name}).second) { + continue; + } + Member member; + member.kind = MemberKind::field; + member.name = std::string {field.name}; + member.detail = fieldText(node, field); + member.field = &field; + out.push_back(std::move(member)); + } + } + for (const NodeInfo* info = node.info(); info != nullptr; info = info->base_type) { + for (const auto& function : info->methods) { + if (!seen.insert(std::string {function.name}).second) { + continue; + } + Member member; + member.kind = MemberKind::function; + member.name = std::string {function.name}; + member.detail = parametersText(function); + member.function = &function; + out.push_back(std::move(member)); + } + } + + if (!seen.contains("enabled")) { + Member member; + member.kind = MemberKind::enabled; + member.name = "enabled"; + member.detail = node.enabled() ? "true" : "false"; + out.push_back(std::move(member)); + seen.insert("enabled"); + } + + if (auto* runtime = node.scriptRuntime()) { + for (size_t i = 0; i < runtime->instanceCount(); ++i) { + if (const auto* schema = runtime->instanceSchema(i)) { + schema->forEach([&](const scripting::LuaVarDesc& variable) { + if (variable.hidden || !seen.insert(variable.name).second) { + return; + } + Member member; + member.kind = MemberKind::lua_variable; + member.name = variable.name; + member.detail = luaKindName(variable.kind); + member.variable = variable; + out.push_back(std::move(member)); + }); + } + } + for (const auto& function : runtime->functions()) { + if (function.name.starts_with('_') || !seen.insert(function.name).second) { + continue; + } + Member member; + member.kind = MemberKind::lua_function; + member.name = function.name; + for (const auto& parameter : function.parameters) { + member.detail += member.detail.empty() ? parameter : "; " + parameter; + } + out.push_back(std::move(member)); + } + } + return out; +} + +auto entryKindOf(MemberKind kind) -> EntryKind { + return kind == MemberKind::function || kind == MemberKind::lua_function ? EntryKind::function : EntryKind::field; +} + +auto handleSetter(const FieldInfo& field, std::string_view text) -> std::optional> { + if (field.value_type != FieldType::uid_t || field.is_array || field.isNodeReference()) { + return std::nullopt; + } + const std::string asset_type = assetTypeOfSpelling(field.type); + if (asset_type.empty()) { + return std::nullopt; + } + const auto uid = assetByPath(text, asset_type); + if (!uid) { + return std::unexpected(uid.error()); + } + return Setter {[name = std::string {field.name}, uid = *uid](Node& n) { n.set(name, uid); }}; +} + +auto bodyMover(const Node& node, const FieldInfo& field, std::string_view text) -> std::optional { + if (node.info() == nullptr || field.is_array) { + return std::nullopt; + } + std::vector names; + if (field.name == "position" && field.value_type == FieldType::vec3_t) { + names = {"teleport", "setPosition"}; + } else if (field.name == "rotation" && field.value_type == FieldType::quaternion_t) { + names = {"setRotation"}; + } + for (const std::string_view name : names) { + const FunctionInfo* method = node.info()->getMethod(name); + if (method == nullptr || method->parameters.size() != 1) { + continue; + } + std::any value; + if (field.value_type == FieldType::vec3_t) { + const auto vector = scalarFrom(text, Type::vec3); + if (!vector) { + return std::nullopt; + } + value = std::get(*vector); + } else { + const auto rotation = quatFrom(text); + if (!rotation) { + return std::nullopt; + } + value = *rotation; + } + return Setter {[name = std::string {name}, value = std::move(value)](Node& target) { + std::vector arguments {value}; + try { + (void)target.info()->callAllDynamic(&target, name, arguments); + } catch (const std::exception& e) { TOAST_WARN("Console", "{} failed: {}", name, e.what()); } + }}; + } + return std::nullopt; +} + +auto typeOf(FieldType type) -> std::optional { + switch (type) { + case FieldType::bool_t: return Type::boolean; + case FieldType::int_t: return Type::integer; + case FieldType::float_t: + case FieldType::double_t: return Type::floating; + case FieldType::string_t: return Type::string; + case FieldType::vec2_t: return Type::vec2; + case FieldType::vec3_t: return Type::vec3; + case FieldType::vec4_t: return Type::vec4; + case FieldType::quaternion_t: return Type::quat; + default: return std::nullopt; + } +} + +auto typeOf(scripting::LuaVarKind kind) -> std::optional { + using scripting::LuaVarKind; + switch (kind) { + case LuaVarKind::boolean: return Type::boolean; + case LuaVarKind::integer: return Type::integer; + case LuaVarKind::number: return Type::floating; + case LuaVarKind::string: return Type::string; + case LuaVarKind::vec2: return Type::vec2; + case LuaVarKind::vec3: + case LuaVarKind::color3: return Type::vec3; + case LuaVarKind::vec4: + case LuaVarKind::color4: return Type::vec4; + default: return std::nullopt; + } +} + +} + +auto executeNode(const NodeRoot& root_of, std::string_view arguments) -> Result { + arguments = trim(arguments); + if (arguments.empty()) { + return {false, std::string {k_usage}}; + } + const size_t spec_end = arguments.find_first_of(k_whitespace); + const std::string_view spec = arguments.substr(0, spec_end); + const std::string_view rest = spec_end == std::string_view::npos ? std::string_view {} : trim(arguments.substr(spec_end)); + + const size_t slash = spec.rfind('/'); + const size_t dot = spec.rfind('.'); + const bool has_member = dot != std::string_view::npos && (slash == std::string_view::npos || dot > slash); + const std::string_view path = has_member ? spec.substr(0, dot) : spec; + const std::string_view member_name = has_member ? spec.substr(dot + 1) : std::string_view {}; + + Box root = root_of ? root_of() : Box {}; + Found found = resolve(root, path); + if (!found.node.exists()) { + return {false, found.error}; + } + Node& node = *found.node; + + if (!has_member) { + return {true, std::format("{}: {}, {} children", path, typeName(node), node.children().size())}; + } + if (member_name.empty()) { + return {false, std::format("{}: say what to do with it, after the dot", path)}; + } + + std::vector all; + { + const TreeReadLock lock(node); + all = membersOf(node); + } + std::optional member = findMember(all, member_name); + if (!member) { + std::vector> close; + for (const auto& candidate : all) { + if (const auto score = fuzzyScore(member_name, candidate.name)) { + close.emplace_back(*score, candidate.name); + } + } + std::ranges::sort(close, [](const auto& a, const auto& b) { return a.first > b.first; }); + std::string message = std::format("{} ({}) has no variable or function '{}'", path, typeName(node), member_name); + for (size_t i = 0; i < close.size() && i < 3; ++i) { + if (i == 0) { + message += ", did you mean "; + } else { + message += i + 1 == close.size() || i == 2 ? " or " : ", "; + } + message += close[i].second; + } + message += close.empty() ? "" : "?"; + return {false, std::move(message)}; + } + + const std::string label = std::format("{}.{}", path, member->name); + + switch (member->kind) { + case MemberKind::enabled: { + if (rest.empty()) { + return {true, std::format("{} = {}", label, member->detail)}; + } + std::string text {rest}; + if (hasRelative(rest)) { + auto worked_out = resolveRelative(rest, member->detail, Type::boolean); + if (!worked_out) { + return {false, std::format("{}: {}", label, worked_out.error())}; + } + text = std::move(*worked_out); + } + const auto value = scalarFrom(text, Type::boolean); + if (!value) { + return {false, std::format("{}: {}", label, value.error())}; + } + const bool on = std::get(*value); + enqueue([box = found.node, on]() mutable { + if (box.exists()) { + box->enabled(on); + } + }); + return {true, std::format("{} = {}", label, on ? "true" : "false")}; + } + + case MemberKind::field: { + if (rest.empty()) { + return {true, std::format("{} = {}", label, member->detail)}; + } + // `~` is what it is now + std::string text {rest}; + if (hasRelative(rest)) { + const auto type = typeOf(member->field->value_type); + if (member->field->is_array || !type) { + return {false, std::format("{}: it cannot be written relative to itself", label)}; + } + std::string current; + { + const TreeReadLock lock(node); + current = fieldText(node, *member->field); + } + auto worked_out = resolveRelative(rest, current, *type); + if (!worked_out) { + return {false, std::format("{}: {}", label, worked_out.error())}; + } + text = std::move(*worked_out); + } + auto setter = [&]() -> std::expected { + if (auto handle = handleSetter(*member->field, text)) { + return std::move(*handle); + } + if (auto mover = bodyMover(node, *member->field, text)) { + return std::move(*mover); + } + return fieldSetter(*member->field, text); + }(); + if (!setter) { + return {false, std::format("{}: {}", label, setter.error())}; + } + enqueue([box = found.node, setter = std::move(*setter)]() mutable { + if (box.exists()) { + setter(*box); + } + }); + return {true, std::format("{} = {}", label, text)}; + } + + case MemberKind::lua_variable: { + if (rest.empty()) { + return {true, std::format("{} is a {} of the scripts; give it a value to set it", label, member->detail)}; + } + std::string text {rest}; + if (hasRelative(rest)) { + const auto type = typeOf(member->variable->kind); + auto* runtime = node.scriptRuntime(); + if (member->variable->is_array || !type || runtime == nullptr) { + return {false, std::format("{}: it cannot be written relative to itself", label)}; + } + const std::string current = scripting::stringifyLuaValue(*member->variable, runtime->getVar(member->name)); + auto worked_out = resolveRelative(rest, current, *type); + if (!worked_out) { + return {false, std::format("{}: {}", label, worked_out.error())}; + } + text = std::move(*worked_out); + } + if (member->variable->kind == scripting::LuaVarKind::asset_ref && text.contains("://")) { + const auto uid = assetByPath(text, member->variable->ref_type); + if (!uid) { + return {false, std::format("{}: {}", label, uid.error())}; + } + text = uid->get(); + } + std::any value; + try { + value = scripting::parseLuaValue(*member->variable, text, [](std::string_view) { return Box {}; }); + } catch (const std::exception&) { return {false, std::format("{}: that is not a {}", label, member->detail)}; } + if (!value.has_value()) { + return {false, std::format("{}: that is not a {}", label, member->detail)}; + } + enqueue([box = found.node, name = member->name, value = std::move(value)]() mutable { + if (box.exists()) { + if (auto* runtime = box->scriptRuntime()) { + runtime->setVar(name, value); + } + } + }); + return {true, std::format("{} = {}", label, text)}; + } + + case MemberKind::function: { + const FunctionInfo& function = *member->function; + const auto texts = splitArguments(rest); + size_t required = 0; + for (const auto& parameter : function.parameters) { + required += parameter.default_value ? 0 : 1; + } + if (texts.size() < required || texts.size() > function.parameters.size()) { + return { + false, + std::format("{} takes ({}), separated by ;", label, member->detail.empty() ? std::string {"nothing"} : member->detail) + }; + } + + std::vector values(function.parameters.size()); + for (size_t i = 0; i < texts.size(); ++i) { + auto argument = parseArgument(function.parameters[i], texts[i], root_of); + if (!argument) { + return {false, std::format("{}: {}", label, argument.error())}; + } + values[i] = std::move(*argument); + } + enqueue([box = found.node, name = member->name, values = std::move(values)]() mutable { + if (!box.exists()) { + return; + } + std::vector arguments; + arguments.reserve(values.size()); + for (const auto& value : values) { + arguments.push_back(value.view ? std::any {std::string_view {value.text}} : value.value); + } + try { + if (box->info() != nullptr && box->info()->getMethod(name)) { + (void)box->info()->callAllDynamic(&*box, name, arguments); + } + _detail::callNodeScripts(&*box, name, arguments); + } catch (const std::exception& e) { TOAST_WARN("Console", "{} failed: {}", name, e.what()); } + }); + return {true, std::format("called {}({})", label, rest)}; + } + + case MemberKind::lua_function: { + std::vector values; + for (const auto text : splitArguments(rest)) { + if (text.empty()) { + return {false, std::format("{}: an argument is empty", label)}; + } + values.push_back(guessArgument(text)); + } + enqueue([box = found.node, name = member->name, values = std::move(values)]() mutable { + if (box.exists()) { + _detail::callNodeScripts(&*box, name, values); + } + }); + return {true, std::format("called {}({})", label, rest)}; + } + } + return {false, std::string {k_usage}}; +} + +auto describeNode(const NodeRoot& root_of, std::string_view spec) -> Result { + spec = trim(spec); + const size_t slash = spec.rfind('/'); + const size_t dot = spec.rfind('.'); + if (dot == std::string_view::npos || (slash != std::string_view::npos && dot < slash)) { + return {false, "name a variable of a node: ."}; + } + const std::string_view path = spec.substr(0, dot); + const std::string_view member_name = spec.substr(dot + 1); + + Found found = resolve(root_of ? root_of() : Box {}, path); + if (!found.node.exists()) { + return {false, found.error}; + } + Node& node = *found.node; + std::vector all; + { + const TreeReadLock lock(node); + all = membersOf(node); + } + const auto member = findMember(all, member_name); + if (!member) { + return {false, std::format("{} ({}) has no variable '{}'", path, typeName(node), member_name)}; + } + + switch (member->kind) { + case MemberKind::field: + case MemberKind::enabled: return {true, std::format("{}.{} = {}", path, member->name, member->detail)}; + case MemberKind::lua_variable: { + std::string value = member->detail; + if (auto* runtime = node.scriptRuntime()) { + value = scripting::stringifyLuaValue(*member->variable, runtime->getVar(member->name)); + } + return {true, std::format("{}.{} = {}", path, member->name, value)}; + } + default: return {false, std::format("{}.{} is a function; only a variable can be pinned", path, member->name)}; + } +} + +void runQueuedNodeWork() { + std::vector> work; + { + const std::lock_guard lock(g_queue_mutex); + work.swap(g_queue); + } + for (auto& item : work) { + item(); + } +} + +auto completePath(std::string_view written, size_t begin, std::string_view asset_type) -> Completion { + Completion completion; + if (!assets::AssetManager::isInitialized() || asset_type.empty()) { + return completion; + } + const bool quoted = written.starts_with('"'); + if (quoted) { + written.remove_prefix(1); + ++begin; + } + + std::vector uris; + for (const toast::UID uid : assets::AssetManager::get().listByType(asset_type)) { + if (auto uri = assets::AssetManager::getURI(uid); !uri.empty()) { + uris.push_back(std::move(uri)); + } + } + std::ranges::sort(uris); + + const size_t scheme_end = written.find("://"); + std::vector scored; + std::set offered; + + if (scheme_end == std::string_view::npos) { + completion.replace_begin = begin; + completion.replace_end = begin + written.size(); + for (const auto& uri : uris) { + const std::string scheme = uri.substr(0, uri.find("://")) + "://"; + if (const auto score = fuzzyScore(written, scheme); score && offered.insert(scheme).second) { + scored.push_back({ + {scheme, scheme, {}, EntryKind::node}, + *score + }); + } + } + } else { + const size_t folder_end = written.rfind('/'); + const std::string_view folder = written.substr(0, folder_end + 1); + const std::string_view partial = written.substr(folder_end + 1); + completion.replace_begin = begin + folder.size(); + completion.replace_end = begin + written.size(); + for (const auto& uri : uris) { + if (!uri.starts_with(folder)) { + continue; + } + const std::string_view rest = std::string_view {uri}.substr(folder.size()); + const size_t slash = rest.find('/'); + const bool is_folder = slash != std::string_view::npos; + const std::string name {rest.substr(0, is_folder ? slash : rest.size())}; + const std::string shown = is_folder ? name + "/" : name; + if (const auto score = fuzzyScore(partial, name); score && offered.insert(shown).second) { + scored.push_back({ + {shown, shown, is_folder ? std::string {} : std::string {asset_type}, is_folder ? EntryKind::node : EntryKind::value}, + *score + }); + } + } + } + if (!written.empty()) { + rank(scored); + } + for (auto& item : scored) { + completion.entries.push_back(std::move(item.entry)); + } + return completion; +} + +auto completeNode(const NodeRoot& root_of, std::string_view line, size_t cursor, size_t base) -> Completion { + Completion completion; + Box root = root_of ? root_of() : Box {}; + if (!root.exists()) { + return completion; + } + + const size_t spec_begin = std::min(line.find_first_not_of(k_whitespace, std::min(base, line.size())), line.size()); + size_t spec_end = line.find_first_of(k_whitespace, spec_begin); + if (spec_end == std::string_view::npos) { + spec_end = line.size(); + } + cursor = std::clamp(cursor, spec_begin, line.size()); + + if (cursor > spec_end) { + const std::string_view spec = line.substr(spec_begin, spec_end - spec_begin); + const size_t spec_slash = spec.rfind('/'); + const size_t spec_dot = spec.rfind('.'); + if (spec_dot == std::string_view::npos || (spec_slash != std::string_view::npos && spec_dot < spec_slash)) { + return completion; + } + Found found = resolve(root, spec.substr(0, spec_dot)); + if (!found.node.exists()) { + return completion; + } + std::vector members; + { + const TreeReadLock lock(*found.node); + members = membersOf(*found.node); + } + auto found_member = findMember(members, spec.substr(spec_dot + 1)); + if (!found_member) { + return completion; + } + auto* const member = &*found_member; + + completion.hint = member->detail; + if (member->kind == MemberKind::lua_variable) { + if (auto* runtime = found.node->scriptRuntime()) { + completion.hint = scripting::stringifyLuaValue(*member->variable, runtime->getVar(member->name)); + } + } + + const size_t arguments_begin = std::min(line.find_first_not_of(k_whitespace, spec_end), line.size()); + const size_t from = std::min(arguments_begin, cursor); + const std::string_view written = line.substr(from, cursor - from); + + size_t piece_begin = from; + size_t index = 0; + if (member->kind == MemberKind::function || member->kind == MemberKind::lua_function) { + bool quoted = false; + for (size_t i = 0; i < written.size(); ++i) { + if (written[i] == '\\' && quoted) { + ++i; + } else if (written[i] == '"') { + quoted = !quoted; + } else if (written[i] == ';' && !quoted) { + piece_begin = from + i + 1; + ++index; + } + } + } + const size_t piece_start = std::min(line.find_first_not_of(k_whitespace, piece_begin), cursor); + const std::string_view partial = line.substr(piece_start, cursor - piece_start); + completion.replace_begin = piece_start; + completion.replace_end = cursor; + + std::string asset_type; + if (member->kind == MemberKind::field && member->field->value_type == FieldType::uid_t && !member->field->is_array && + !member->field->isNodeReference()) { + asset_type = assetTypeOfSpelling(member->field->type); + } else if (member->kind == MemberKind::function && index < member->function->parameters.size()) { + if (const HandleKind* kind = handleKindOf(member->function->parameters[index].type_id)) { + asset_type = kind->asset_type; + } + } else if (member->kind == MemberKind::lua_variable && member->variable->kind == scripting::LuaVarKind::asset_ref) { + asset_type = member->variable->ref_type; + } + if (!asset_type.empty()) { + Completion paths = completePath(partial, piece_start, asset_type); + paths.hint = completion.hint; + return paths; + } + + bool boolean = member->kind == MemberKind::enabled; + if (member->kind == MemberKind::field) { + boolean = member->field->value_type == FieldType::bool_t && !member->field->is_array; + } else if (member->kind == MemberKind::function && index < member->function->parameters.size()) { + const auto* id = member->function->parameters[index].type_id; + boolean = id != nullptr && *id == typeid(bool); + } + if (boolean) { + std::vector names; + for (const std::string_view name : {"true", "false"}) { + if (const auto score = fuzzyScore(partial, name)) { + names.push_back({ + {std::string {name}, std::string {name}, {}, EntryKind::value}, + *score + }); + } + } + if (!partial.empty()) { + rank(names); + } + for (auto& item : names) { + completion.entries.push_back(std::move(item.entry)); + } + } + return completion; + } + + const std::string_view written = line.substr(spec_begin, cursor - spec_begin); + const size_t slash = written.rfind('/'); + const size_t dot = written.rfind('.'); + + if (dot != std::string_view::npos && (slash == std::string_view::npos || dot > slash)) { + Found found = resolve(root, written.substr(0, dot)); + if (!found.node.exists()) { + return completion; + } + const std::string_view partial = written.substr(dot + 1); + completion.replace_begin = spec_begin + dot + 1; + completion.replace_end = spec_end; + + std::vector members; + { + const TreeReadLock lock(*found.node); + members = membersOf(*found.node); + } + std::vector fields; + std::vector functions; + for (auto& member : members) { + if (const auto score = fuzzyScore(partial, member.name)) { + const EntryKind kind = entryKindOf(member.kind); + (kind == EntryKind::field ? fields : functions) + .push_back({ + {member.name, member.name, std::move(member.detail), kind}, + *score + }); + } + } + append(completion.entries, fields); + append(completion.entries, functions); + return completion; + } + + const std::string_view partial = slash == std::string_view::npos ? written : written.substr(slash + 1); + completion.replace_begin = spec_begin + (slash == std::string_view::npos ? 0 : slash + 1); + completion.replace_end = std::min(spec_end, std::max(cursor, line.find_first_of("/.", cursor))); + + struct Seen { + std::string type; + size_t count = 0; + }; + + std::vector> names; + const auto note = [&](const Node& node) { + const std::string name = typed(node.name()); + const auto at = std::ranges::find(names, name, &std::pair::first); + if (at == names.end()) { + names.push_back({ + name, {typeName(node), 1} + }); + } else { + ++at->second.count; + } + }; + + if (slash == std::string_view::npos) { + const TreeReadLock lock(*root); + names.push_back({ + "world", {typeName(*root), 1} + }); + names.push_back({ + "global", {"anywhere", 1} + }); + for (const auto& child : root->children()) { + note(*child); + } + } else if (written.substr(0, slash) == "global") { + const TreeReadLock lock(*root); + const auto walk = [&](this auto&& self, const Node& node) -> void { + note(node); + for (const auto& child : node.children()) { + self(*child); + } + }; + walk(*root); + } else { + Found scope = resolve(root, written.substr(0, slash)); + if (!scope.node.exists()) { + return completion; + } + const TreeReadLock lock(*scope.node); + for (const auto& child : scope.node->children()) { + note(*child); + } + } + + std::vector scored; + for (auto& [name, seen] : names) { + if (name.empty()) { + continue; + } + if (const auto score = fuzzyScore(partial, name)) { + std::string type = seen.type; + if (seen.count > 1 && name != "world" && name != "global") { + type += std::format(" x{}", seen.count); + } + scored.push_back({ + {name, name, std::move(type), EntryKind::node}, + *score + }); + } + } + append(completion.entries, scored); + return completion; +} + +} diff --git a/engine/src/toast/console/node_command.hpp b/engine/src/toast/console/node_command.hpp new file mode 100644 index 000000000..8cf554426 --- /dev/null +++ b/engine/src/toast/console/node_command.hpp @@ -0,0 +1,29 @@ +/** + * @file node_command.hpp + * @author Xein + * @date 25 Nov 2026 + * + * @brief The `node` command + */ + +#pragma once +#include "model.hpp" + +#include +#include + +namespace toast::console { + +using NodeRoot = std::function()>; + +[[nodiscard]] +auto completeNode(const NodeRoot& root, std::string_view line, size_t cursor, size_t base) -> Completion; + +auto executeNode(const NodeRoot& root, std::string_view arguments) -> Result; + +[[nodiscard]] +auto describeNode(const NodeRoot& root, std::string_view spec) -> Result; + +void runQueuedNodeWork(); + +} diff --git a/engine/src/toast/console/palette.hpp b/engine/src/toast/console/palette.hpp new file mode 100644 index 000000000..34c1cf78f --- /dev/null +++ b/engine/src/toast/console/palette.hpp @@ -0,0 +1,36 @@ +/** + * @file palette.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief The editor's colors (editor/Resources/EditorColors.axaml) + */ + +#pragma once +#include + +namespace toast::console::palette { + +struct Color { + uint8_t r; + uint8_t g; + uint8_t b; +}; + +inline constexpr Color k_bg1 {0x12, 0x11, 0x11}; +inline constexpr Color k_bg2 {0x1F, 0x1D, 0x1E}; +inline constexpr Color k_bg3 {0x2B, 0x2A, 0x2A}; +inline constexpr Color k_bg4 {0x38, 0x36, 0x37}; +inline constexpr Color k_bg5 {0x45, 0x43, 0x43}; + +inline constexpr Color k_text {0xFA, 0xFA, 0xFA}; +inline constexpr Color k_text_muted {0xA0, 0xA0, 0xA0}; + +inline constexpr Color k_red {0xFF, 0x16, 0x59}; +inline constexpr Color k_green {0x00, 0xFF, 0x40}; +inline constexpr Color k_blue {0x29, 0xAD, 0xFF}; +inline constexpr Color k_magenta {0xAD, 0x73, 0xFF}; +inline constexpr Color k_orange {0xFF, 0xA3, 0x00}; +inline constexpr Color k_cyan {0x73, 0xFF, 0xEA}; + +} diff --git a/engine/src/toast/console/ranking.hpp b/engine/src/toast/console/ranking.hpp new file mode 100644 index 000000000..f36479ab7 --- /dev/null +++ b/engine/src/toast/console/ranking.hpp @@ -0,0 +1,35 @@ +/** + * @file ranking.hpp + * @author Xein + * @date 25 Nov 2026 + * + * @brief Putting the entries of the popup in order + */ + +#pragma once +#include "model.hpp" + +#include +#include + +namespace toast::console { + +struct Scored { + Entry entry; + int score = 0; +}; + +inline void rank(std::vector& scored) { + std::ranges::stable_sort(scored, [](const Scored& a, const Scored& b) { + return a.score != b.score ? a.score > b.score : a.entry.label < b.entry.label; + }); +} + +inline void append(std::vector& out, std::vector& scored) { + rank(scored); + for (auto& item : scored) { + out.push_back(std::move(item.entry)); + } +} + +} diff --git a/engine/src/toast/console/relative.cpp b/engine/src/toast/console/relative.cpp new file mode 100644 index 000000000..c6be5ff4b --- /dev/null +++ b/engine/src/toast/console/relative.cpp @@ -0,0 +1,176 @@ +#include "relative.hpp" + +#include +#include +#include +#include +#include +#include + +namespace toast::console { +namespace { + +using toast::params::Type; +using Result = std::expected; + +constexpr std::string_view k_whitespace = " \t"; + +auto trim(std::string_view text) -> std::string_view { + const size_t first = text.find_first_not_of(k_whitespace); + if (first == std::string_view::npos) { + return {}; + } + return text.substr(first, text.find_last_not_of(k_whitespace) - first + 1); +} + +auto words(std::string_view text) -> std::vector { + std::vector out; + size_t at = 0; + while (at < text.size()) { + const size_t begin = text.find_first_not_of(k_whitespace, at); + if (begin == std::string_view::npos) { + break; + } + const size_t end = std::min(text.find_first_of(k_whitespace, begin), text.size()); + out.push_back(text.substr(begin, end - begin)); + at = end; + } + return out; +} + +auto number(std::string_view text) -> std::optional { + if (text.starts_with('+')) { + text.remove_prefix(1); + } + double value = 0.0; + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value); + if (error != std::errc {} || end != text.data() + text.size() || text.empty()) { + return std::nullopt; + } + return value; +} + +auto partsOf(Type type) -> size_t { + switch (type) { + case Type::vec2: return 2; + case Type::vec3: return 3; + case Type::vec4: return 4; + default: return 1; + } +} + +auto part(std::string_view token, std::string_view current, bool whole) -> Result { + if (token == "~") { + return std::string {current}; + } + if (!token.starts_with('~')) { + return std::string {token}; + } + if (token.size() < 2 || !std::string_view {"+-*/"}.contains(token[1])) { + return std::unexpected(std::format("'{}': after ~ comes +, -, * or /", token)); + } + const char op = token[1]; + const std::string_view operand_text = token.substr(2); + if (operand_text.empty()) { + return std::unexpected(std::format("'{}' needs a number after the {}", token, op)); + } + const auto operand = number(operand_text); + if (!operand) { + return std::unexpected(std::format("'{}' is not a number", operand_text)); + } + const auto base = number(current); + if (!base) { + return std::unexpected(std::format("'{}' is not a number to start from", current)); + } + + double result = 0.0; + switch (op) { + case '+': result = *base + *operand; break; + case '-': result = *base - *operand; break; + case '*': result = *base * *operand; break; + default: + if (*operand == 0.0) { + return std::unexpected("it cannot be divided by zero"); + } + result = *base / *operand; + break; + } + if (whole) { + return std::format("{}", static_cast(std::trunc(result))); + } + return std::format("{:.9g}", result); +} + +} + +auto hasRelative(std::string_view text) -> bool { + bool quoted = false; + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] == '\\' && quoted) { + ++i; + } else if (text[i] == '"') { + quoted = !quoted; + } else if (text[i] == '~' && !quoted) { + return true; + } + } + return false; +} + +auto resolveRelative(std::string_view typed, std::string_view current, Type type) -> Result { + if (!hasRelative(typed)) { + return std::string {typed}; + } + const std::string_view text = trim(typed); + + switch (type) { + case Type::boolean: + if (text == "~") { + return std::string {current}; + } + if (text == "!~") { + return std::string {current == "true" || current == "on" ? "false" : "true"}; + } + return std::unexpected("a boolean takes ~ to repeat it or !~ to flip it"); + case Type::string: + case Type::asset: + if (text == "~") { + return std::string {current}; + } + return std::unexpected("a text can only repeat itself with ~"); + case Type::quat: return std::unexpected("a rotation cannot be written relative to itself"); + default: break; + } + + if (text.contains("!~")) { + return std::unexpected("only a boolean can be flipped with !~"); + } + + const size_t count = partsOf(type); + const auto typed_parts = words(text); + auto current_parts = words(current); + if (type == Type::integer && count == 1 && text == "~") { + return std::string {current}; + } + if (current_parts.size() != count) { + return std::unexpected(std::format("it has {} parts, not {}", current_parts.size(), count)); + } + if (typed_parts.size() != 1 && typed_parts.size() != count) { + return std::unexpected(std::format("expected {} values, got {}", count, typed_parts.size())); + } + + const bool whole = type == Type::integer; + std::string out; + for (size_t i = 0; i < count; ++i) { + const std::string_view token = typed_parts.size() == 1 ? typed_parts.front() : typed_parts[i]; + auto resolved = part(token, current_parts[i], whole); + if (!resolved) { + return resolved; + } + out += i == 0 ? "" : " "; + out += *resolved; + } + return out; +} + +} diff --git a/engine/src/toast/console/relative.hpp b/engine/src/toast/console/relative.hpp new file mode 100644 index 000000000..802e8d307 --- /dev/null +++ b/engine/src/toast/console/relative.hpp @@ -0,0 +1,25 @@ +/** + * @file relative.hpp + * @author Xein + * @date 25 Nov 2026 + * + * @brief Values typed relative to what is there now + */ + +#pragma once +#include +#include +#include +#include +#include + +namespace toast::console { + +[[nodiscard]] +TOAST_API auto hasRelative(std::string_view text) -> bool; + +[[nodiscard]] +TOAST_API auto resolveRelative(std::string_view typed, std::string_view current, toast::params::Type type) + -> std::expected; + +} diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index 411308916..0bbaa2e0e 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -25,12 +25,22 @@ #if defined(TOAST_DEV_TOOLS) #include "toast/renderer/passes/debug/debug_pass.hpp" #endif +#include "console/console.hpp" +#include "params/files.hpp" +#include "params/migrate.hpp" +#include "params/pack_source.hpp" +#include "params/registry.hpp" +#include "renderer/settings/renderer_params.hpp" #include "scripting/lua_state.hpp" #include "scripting/script_dispatch.hpp" #include "scripting/script_runtime.hpp" -#include "settings/settings.hpp" +#include "time_params.hpp" +#include "toast/assets/asset_params.hpp" +#include "toast/events/event_params.hpp" +#include "toast/input/input_params.hpp" #include "toast/renderer/output/sdl_output_target.hpp" #include "toast/renderer/output/shared_texture_output_target.hpp" +#include "toast/renderer/passes/debug/console_pass.hpp" #include "toast/renderer/passes/debug/grid_pass.hpp" #include "toast/renderer/passes/geometry/voxel_pass.hpp" #include "toast/renderer/passes/lighting/environment_pass.hpp" @@ -53,6 +63,10 @@ #include "toast/renderer/shaders/shader_compiler.hpp" #include "toast/renderer/shaders/shader_layout.hpp" #include "toast/renderer/vulkan_renderer.hpp" +#include "toast/scripting/scripting_params.hpp" +#include "toast/voxel/voxel_params.hpp" +#include "toast/world/editor_params.hpp" +#include "toast/world/world_params.hpp" #include "ui/render/ui_pass.hpp" #include "ui/render/world_ui_pass.hpp" #include "ui/ui_system.hpp" @@ -61,6 +75,7 @@ #include "window/startup_splash.hpp" #include "window/window_events.hpp" #include "world/camera.hpp" +#include "world/fly_camera.hpp" #include "world/play_workspace.hpp" #include "world/workspace.hpp" #include "world/workspace_events.hpp" @@ -183,6 +198,7 @@ struct EnginePimpl { std::unique_ptr logger = nullptr; std::unique_ptr window = nullptr; std::unique_ptr world = nullptr; + std::unique_ptr fly_camera = nullptr; std::unique_ptr asset_manager = nullptr; std::unique_ptr input_system = nullptr; std::unique_ptr haptics_system = nullptr; @@ -192,6 +208,7 @@ struct EnginePimpl { std::unique_ptr audio_system = nullptr; std::unique_ptr ui_system = nullptr; std::unique_ptr settings = nullptr; + std::unique_ptr params_files = nullptr; std::unique_ptr lua_state = nullptr; std::unique_ptr physics_simulator = nullptr; // owned by renderer's output target @@ -240,6 +257,58 @@ auto Engine::get() noexcept -> Engine* { return instance; } +static auto legacyUserSettingsFile(const std::filesystem::path& toast_path) -> std::filesystem::path { + std::string app_name = "Toast"; + if (std::error_code ec; std::filesystem::is_regular_file(toast_path, ec)) { + std::ifstream in(toast_path, std::ios::binary); + std::stringstream buffer; + buffer << in.rdbuf(); + if (auto document = params::tomlToDocument(buffer.str()); + document && document->contains("name") && (*document)["name"].is_string()) { + app_name = (*document)["name"].get(); + } + } + + std::filesystem::path user_file; + if (char* pref_path = SDL_GetPrefPath("nullptr-studios", app_name.c_str())) { + user_file = std::filesystem::path(pref_path) / "settings.toml"; + auto game_dir = std::filesystem::path(pref_path); + if (!game_dir.has_filename()) { + game_dir = game_dir.parent_path(); + } + const auto older_file = game_dir.parent_path().parent_path() / "Nullptr Studios" / app_name / "settings.toml"; + std::error_code ec; + if (std::filesystem::exists(older_file, ec) && !std::filesystem::exists(user_file, ec)) { + std::filesystem::copy_file(older_file, user_file, ec); + } + SDL_free(pref_path); + } + return user_file; +} + +static auto savedConfigDirectory(const std::filesystem::path& toast_path) -> std::filesystem::path { + if (const auto& saved = assets::AssetManager::savedRoot(); !saved.empty()) { + return saved / "config"; + } + + std::string app_name = "Toast"; + if (std::error_code ec; std::filesystem::is_regular_file(toast_path, ec)) { + std::ifstream in(toast_path, std::ios::binary); + std::stringstream buffer; + buffer << in.rdbuf(); + if (auto document = params::tomlToDocument(buffer.str()); + document && document->contains("name") && (*document)["name"].is_string()) { + app_name = (*document)["name"].get(); + } + } + std::filesystem::path result; + if (char* pref_path = SDL_GetPrefPath("nullptr-studios", app_name.c_str())) { + result = std::filesystem::path(pref_path) / "config"; + SDL_free(pref_path); + } + return result; +} + void Engine::init() { ZoneScoped; TracySetProgramName("ToastEngine"); @@ -248,6 +317,22 @@ void Engine::init() { #endif event::registerProtoEvents(); + + console::Console::get().attach(); + console::Console::get().setAssetCheck([](std::string_view uri) { + return !assets::AssetManager::isInitialized() || assets::AssetManager::resolveURI(uri).has_value(); + }); + console::Console::get().setNodeRoot([this]() -> Box { + { + std::scoped_lock lock(m->owners_mutex); + if (const auto it = m->owners.find(m->active_workspace); it != m->owners.end()) { + if (Workspace* workspace = it->second->asWorkspace(); workspace != nullptr && workspace->isValid()) { + return workspace->rootBox(); + } + } + } + return World::root(); + }); registerEngineTypes(); // Find the first .toast project file in the project root and load settings @@ -262,7 +347,41 @@ void Engine::init() { } } } - m->settings = std::make_unique(toast_path); + const auto& config_dir = assets::AssetManager::configRoot(); + const auto config_pak = proj_root / "configs.pak"; + const bool packaged = std::filesystem::is_regular_file(config_pak); + + const auto saved_config_dir = savedConfigDirectory(toast_path); + if (!packaged && !toast_path.empty()) { + params::migrateProjectToast(toast_path, config_dir); + } + if (!packaged) { + params::upgradeLegacyConfig(config_dir); + } + if (const auto old_user_file = legacyUserSettingsFile(toast_path); !old_user_file.empty() && !saved_config_dir.empty()) { + params::migrateLegacyUserSettings(old_user_file, saved_config_dir); + } + + m->params_files = std::make_unique( + params::openProjectSource(config_dir, config_pak), std::make_unique(saved_config_dir) + ); + + auto& registry = params::Registry::get(); + registry.setLayerPath(params::Layer::project, config_dir.string()); + registry.setLayerPath(params::Layer::saved, saved_config_dir.string()); + registry.setSaveHandler([this] { + if (m && m->params_files) { + m->params_files->saveDirty(); + } + }); + registry.setRestoreHandler([this] { + if (m && m->params_files) { + m->params_files->reload(); + } + }); + + m->settings.reset(); + m->settings = std::make_unique(toast_path, m->params_files.get()); } // Register content database VFS roots derived from project settings @@ -273,35 +392,25 @@ void Engine::init() { } } - // User settings { - auto& settings = settings::Settings::get(); - const auto& proj_root = assets::AssetManager::projectRoot(); - - std::filesystem::path user_file; - const std::string app_name {ProjectSettings::name().empty() ? "Toast" : ProjectSettings::name()}; - if (char* pref_path = SDL_GetPrefPath("nullptr-studios", app_name.c_str())) { - user_file = std::filesystem::path(pref_path) / "settings.toml"; - auto game_dir = std::filesystem::path(pref_path); - if (!game_dir.has_filename()) { - game_dir = game_dir.parent_path(); - } - const auto legacy_file = game_dir.parent_path().parent_path() / "Nullptr Studios" / app_name / "settings.toml"; - std::error_code ec; - if (std::filesystem::exists(legacy_file, ec) && !std::filesystem::exists(user_file, ec)) { - std::filesystem::copy_file(legacy_file, user_file, ec); - } - SDL_free(pref_path); - } - - settings.setPaths(toast_path, user_file); - settings.load(); - // Before the renderer exists, ShadowPass reads its resolution when it allocates, so this cannot wait // for the rest of the renderer settings renderer::registerRendererStartupSettings(); physics::registerPhysicsSettings(); + (void)editorParams(); + (void)assets::assetParams(); + (void)input::inputParams(); + (void)scripting::scriptingParams(); + (void)voxel::voxelParams(); + (void)event::eventParams(); + (void)worldParams(); + (void)timeParams(); + + m->params_files->reload(); + + toast::params::onChange(timeParams().scale, [](const float& value) { Time::scale(value); }); + toast::params::onChange(timeParams().max_delta, [](const float& value) { Time::setMaxDelta(value); }); } m->asset_manager = std::make_unique(); @@ -389,7 +498,11 @@ Engine::~Engine() noexcept { if (m) { // Save settings before closing down try { - settings::Settings::get().saveIfDirty(); + if (m->params_files) { + m->params_files->saveDirty(); + } + params::Registry::get().setSaveHandler(nullptr); + params::Registry::get().setRestoreHandler(nullptr); } catch (const std::exception& e) { TOAST_ERROR("Engine", "Failed to save settings on shutdown: {}", e.what()); } // Stops the render thread and waits for anything still building @@ -402,6 +515,8 @@ Engine::~Engine() noexcept { std::scoped_lock lock(m->owners_mutex); m->owners.clear(); } + console::Console::get().setNodeRoot({}); + m->fly_camera.reset(); m->world.reset(); m->ui_system.reset(); m->input_system.reset(); @@ -436,7 +551,8 @@ void Engine::reloadSettings() { // Clear old content database routes and reload settings assets::AssetManager::clearDatabases(); - m->settings = std::make_unique(toast_path); + m->settings.reset(); + m->settings = std::make_unique(toast_path, m->params_files.get()); // Re-register content databases from updated settings for (const auto& db : ProjectSettings::databases()) { @@ -511,6 +627,11 @@ void Engine::tick() { } m->time.tick(); + params::Registry::get().applyPending(); + + console::Model::applyQueued(); + console::Console::get().updatePins(); + // Poll window events if (m->window) { m->window->pollEvents(); @@ -535,6 +656,15 @@ void Engine::tick() { } scripting::ScriptDispatch::deliver(); + if (!m->fly_camera) { + m->fly_camera = std::make_unique(); + } + m->fly_camera->tick(static_cast(Time::delta())); + + if (m->physics_simulator) { + m->physics_simulator->drawDebugVisuals(); + } + // Run application layer if (active_application) { ZoneScopedN("GameLayer::tick()"); @@ -552,7 +682,8 @@ void Engine::tick() { // TODO MOVE THIS // FIXME: @XEIN where should we move this?? clear_assets_timer += Time::delta(); - if (clear_assets_timer > 30.0) { + const double unload_interval = assets::assetParams().unload_interval; + if (unload_interval > 0.0 && clear_assets_timer > unload_interval) { m->asset_manager->clearUnusedAssets(); clear_assets_timer = 0.0; } @@ -656,7 +787,8 @@ void Engine::tick() { // The reloads are only applied in the editor while nothing is playing if (m->shared_target != nullptr && m->asset_manager && !gameIsAdvancing(*m)) { script_reload_timer += Time::delta(); - if (script_reload_timer > 1.0) { + const auto& reload = assets::assetParams(); + if (reload.hot_reload_enabled && script_reload_timer > reload.hot_reload_interval) { script_reload_timer = 0.0; m->asset_manager->pollModifiedAssets(); } @@ -719,8 +851,7 @@ void Engine::createSDLWindow(const char* w_name) { // Reads true only once the window is shown const SDLWindow::DisplayHdr display_hdr = SDLWindow::queryDisplayHdr(sdl_window); - const auto hdr_setting = settings::Settings::get().value(renderer::k_hdr_output); - const bool prefer_hdr = display_hdr.enabled && (!hdr_setting.has_value() || std::get(*hdr_setting)); + const bool prefer_hdr = display_hdr.enabled && renderer::rendererParams().display_hdr; TOAST_INFO( "Render", "Display HDR {} (SDR white {:.2f}, headroom {:.2f}), HDR output {}", @@ -762,6 +893,8 @@ void Engine::createSDLWindow(const char* w_name) { m->renderer->addRenderPass(std::move(debug_pass)); #endif + m->renderer->addRenderPass(std::make_unique(*m->vulkan_core, color_format, depth_format)); + // FIXME: CAPPED AT 240 for now m->renderer->setFrameRateLimit(240.0); @@ -772,7 +905,7 @@ void Engine::createSDLWindow(const char* w_name) { void Engine::createAvaloniaWindow() { ZoneScoped; - settings::Settings::get().setActiveLayer(settings::Layer::project); + params::Registry::get().setAuthoringLayer(params::Layer::project); m->vulkan_core = std::make_unique(std::span {}, std::span {}); @@ -820,6 +953,8 @@ void Engine::createAvaloniaWindow() { m->renderer->setUIFrameBuilder([ui = m->ui_system.get()](renderer::RenderFrame& frame) { ui->buildDrawFrame(frame); }); } + m->renderer->addRenderPass(std::make_unique(*m->vulkan_core, color_format, depth_format)); + // editor will always be capped m->renderer->setFrameRateLimit(240.0); @@ -1287,6 +1422,10 @@ void toast_set_show_debug_windows(int visible) noexcept { } } +auto toast_console_is_open() noexcept -> int { + return toast::console::Console::get().isOpen() ? 1 : 0; +} + auto toast_debug_overlay_owns_cursor() noexcept -> int { const auto* vk_renderer = renderer::VulkanRenderer::instance; return vk_renderer != nullptr && vk_renderer->debugOverlayOwnsCursor() ? 1 : 0; diff --git a/engine/src/toast/events/event.cpp b/engine/src/toast/events/event.cpp index f983c8d9c..2715d834c 100644 --- a/engine/src/toast/events/event.cpp +++ b/engine/src/toast/events/event.cpp @@ -1,9 +1,13 @@ #include "event.hpp" +#include "event_params.hpp" #include "proto_event.hpp" #include +#include #include +#include +#include namespace event { @@ -68,8 +72,22 @@ void pollEvents() noexcept { } // notify events + const EventParams& params = eventParams(); + const bool log_all = params.log_dispatch; + const float slow_limit_ms = params.slow_warning; for (auto& event : pools[idx].queue) { - event->notify(); + if (!log_all && slow_limit_ms <= 0.0F) { + event->notify(); + } else { + const auto started = std::chrono::steady_clock::now(); + event->notify(); + const float took_ms = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); + if (log_all) { + TOAST_INFO("Events", "{} took {:.3f} ms", typeid(*event).name(), took_ms); + } else if (took_ms > slow_limit_ms) { + TOAST_WARN("Events", "{} took {:.2f} ms to dispatch", typeid(*event).name(), took_ms); + } + } std::destroy_at(event); } diff --git a/engine/src/toast/events/event_params.cpp b/engine/src/toast/events/event_params.cpp new file mode 100644 index 000000000..886b84f3d --- /dev/null +++ b/engine/src/toast/events/event_params.cpp @@ -0,0 +1,10 @@ +#include "event_params.hpp" + +namespace event { + +auto eventParams() -> EventParams& { + static EventParams instance; + return instance; +} + +} diff --git a/engine/src/toast/events/event_params.hpp b/engine/src/toast/events/event_params.hpp new file mode 100644 index 000000000..250603165 --- /dev/null +++ b/engine/src/toast/events/event_params.hpp @@ -0,0 +1,34 @@ +/** + * @file event_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief What the event system reports about itself + */ + +#pragma once +#include +#include + +namespace event { + +struct EventParams : toast::params::Group<"events"> { + using Kind = toast::params::Kind; + + float slow_warning = param( + &slow_warning, "dispatch.slow_warning", 0.0F, + {.name = "Slow event warning", + .min = 0.0F, + .max = 1000.0F, + .unit = "ms", + .description = "Log an event whose listeners take longer than this. 0 is off"} + ); + bool log_dispatch = param( + &log_dispatch, "dispatch.log", false, + {.name = "Log events", .kind = Kind::debug, .description = "Write the type of every event as it is dispatched"} + ); +}; + +TOAST_API auto eventParams() -> EventParams&; + +} diff --git a/engine/src/toast/input/haptics_system.cpp b/engine/src/toast/input/haptics_system.cpp index 4972dd7b8..f9ecdc5f1 100644 --- a/engine/src/toast/input/haptics_system.cpp +++ b/engine/src/toast/input/haptics_system.cpp @@ -1,6 +1,7 @@ #include "haptics_system.hpp" #include "input_events.hpp" +#include "input_params.hpp" #include "input_system.hpp" #include @@ -9,8 +10,6 @@ namespace input { namespace { -constexpr uint32_t rumble_slack_ms = 50; - auto toRumble(float value) -> uint16_t { return static_cast(std::clamp(value, 0.0f, 1.0f) * 65535.0f); } @@ -85,12 +84,14 @@ void HapticsSystem::tick() { }; std::unordered_map per_controller; + const InputParams& params = inputParams(); + const float strength = params.haptics_enabled ? m_global_multiplier * params.haptics_strength : 0.0f; for (const auto& pb : m_playbacks) { const assets::Haptic& haptic = *pb.haptic; const float duration = haptic.durationMs() / 1000.0f; const float t01 = duration > 0.0f ? std::clamp(pb.elapsed / duration, 0.0f, 1.0f) : 0.0f; - const glm::vec2 motors = haptic.sample(t01) * m_global_multiplier; + const glm::vec2 motors = haptic.sample(t01) * strength; const int priority = haptic.priority(); auto it = per_controller.find(pb.controller); @@ -103,7 +104,7 @@ void HapticsSystem::tick() { } } - const uint32_t slice = static_cast(Time::delta() * 1000.0f) + rumble_slack_ms; + const uint32_t slice = static_cast(Time::delta() * 1000.0f) + static_cast(params.haptics_slack); std::unordered_set active_now; for (const auto& [controller, blend] : per_controller) { SDL_Gamepad* pad = SDL_GetGamepadFromID(controller); diff --git a/engine/src/toast/input/input_params.cpp b/engine/src/toast/input/input_params.cpp new file mode 100644 index 000000000..a9716c24f --- /dev/null +++ b/engine/src/toast/input/input_params.cpp @@ -0,0 +1,10 @@ +#include "input_params.hpp" + +namespace input { + +auto inputParams() -> InputParams& { + static InputParams instance; + return instance; +} + +} diff --git a/engine/src/toast/input/input_params.hpp b/engine/src/toast/input/input_params.hpp new file mode 100644 index 000000000..70df70c03 --- /dev/null +++ b/engine/src/toast/input/input_params.hpp @@ -0,0 +1,49 @@ +/** + * @file input_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief How the game reads the mouse + */ + +#pragma once +#include +#include + +namespace input { + +struct InputParams : toast::params::Group<"input"> { + using Kind = toast::params::Kind; + + float mouse_sensitivity = param( + &mouse_sensitivity, "mouse.sensitivity", 1.0F, + {.name = "Sensitivity", .min = 0.05F, .max = 10.0F, .description = "Scales mouse movement"} + ); + float mouse_scroll_speed = param( + &mouse_scroll_speed, "mouse.scroll_speed", 1.0F, + {.name = "Scroll speed", .min = 0.1F, .max = 10.0F, .description = "Scales the wheel"} + ); + float gamepad_activity_threshold = param( + &gamepad_activity_threshold, "gamepad.activity_threshold", 0.5F, + {.name = "Wake threshold", .min = 0.05F, .max = 1.0F, .description = "Stick push that switches prompts to the gamepad"} + ); + bool haptics_enabled = + param(&haptics_enabled, "haptics.enabled", true, {.name = "Rumble", .description = "Controller vibration"}); + float haptics_strength = param( + &haptics_strength, "haptics.strength", 1.0F, + {.name = "Rumble strength", .min = 0.0F, .max = 2.0F, .description = "Scales every rumble"} + ); + int32_t haptics_slack = param( + &haptics_slack, "haptics.slack", 50, + {.name = "Rumble slack", + .min = 0, + .max = 500, + .unit = "ms", + .kind = Kind::advanced, + .description = "Extra time a rumble is kept on past each frame"} + ); +}; + +TOAST_API auto inputParams() -> InputParams&; + +} diff --git a/engine/src/toast/input/input_system.cpp b/engine/src/toast/input/input_system.cpp index ca752357f..85c282e82 100644 --- a/engine/src/toast/input/input_system.cpp +++ b/engine/src/toast/input/input_system.cpp @@ -9,6 +9,7 @@ #include "input_system.hpp" #include "input_events.hpp" +#include "input_params.hpp" #include #include @@ -23,7 +24,6 @@ namespace input { namespace { constexpr float axis_normalize = 32767.0f; -constexpr float controller_activity_threshold = 0.5f; auto toModifierKey(uint16_t sdl_mods) -> ModifierKey { ModifierKey mods = ModifierKey::none; @@ -148,7 +148,7 @@ void InputSystem::subscribeEvents() { if (m_overlay_mouse) { return false; } - m_scroll += glm::vec2 {e.x, e.y}; + m_scroll += glm::vec2 {e.x, e.y} * inputParams().mouse_scroll_speed; noteLastInput(Device::mouse, "mouse"); return false; }); @@ -234,7 +234,7 @@ void InputSystem::refreshGamepads() { } for (int a = 0; a < SDL_GAMEPAD_AXIS_COUNT && !active; ++a) { const float v = static_cast(SDL_GetGamepadAxis(pad, static_cast(a))) / axis_normalize; - active = std::abs(v) >= controller_activity_threshold; + active = std::abs(v) >= inputParams().gamepad_activity_threshold; } if (active) { noteLastInput(Device::controller, gamepadName(pad)); @@ -352,7 +352,7 @@ void InputSystem::tick() { m_last_tick = now; m_has_last_tick = true; - m_mouse_delta = m_mouse_position - m_prev_mouse_position; + m_mouse_delta = (m_mouse_position - m_prev_mouse_position) * inputParams().mouse_sensitivity; refreshGamepads(); diff --git a/engine/src/toast/params/cook.cpp b/engine/src/toast/params/cook.cpp new file mode 100644 index 000000000..40971d992 --- /dev/null +++ b/engine/src/toast/params/cook.cpp @@ -0,0 +1,77 @@ +#include "cook.hpp" + +#include "document.hpp" + +#include +#include +#include +#include +#include + +namespace toast::params { +namespace { + +auto readAll(const std::filesystem::path& path) -> std::string { + std::ifstream in(path, std::ios::binary); + std::stringstream buffer; + buffer << in.rdbuf(); + return buffer.str(); +} + +} + +auto cookConfigs( + const std::filesystem::path& config_dir, const std::filesystem::path& toast_file, const std::filesystem::path& stage_dir +) -> bool { + namespace fs = std::filesystem; + std::error_code ec; + const bool has_config = fs::is_directory(config_dir, ec); + const bool has_toast = fs::is_regular_file(toast_file, ec); + if (!has_config && !has_toast) { + TOAST_ERROR("Params", "Nothing to cook: no {} and no {}", config_dir.string(), toast_file.string()); + return false; + } + + std::vector> outputs; + const auto convert = [&](const fs::path& from, std::string name) { + auto parsed = tomlToDocument(readAll(from)); + if (!parsed) { + TOAST_ERROR("Params", "Cannot cook {}: {}", from.string(), parsed.error()); + return false; + } + outputs.emplace_back(std::move(name), std::move(*parsed)); + return true; + }; + + if (has_config) { + std::vector files; + for (const auto& entry : fs::directory_iterator(config_dir, ec)) { + if (entry.is_regular_file() && entry.path().extension() == ".toml") { + files.push_back(entry.path()); + } + } + std::ranges::sort(files); + for (const auto& file : files) { + if (!convert(file, file.stem().string() + ".bson")) { + return false; + } + } + } + if (has_toast && !convert(toast_file, "project.toast.bson")) { + return false; + } + + fs::create_directories(stage_dir, ec); + for (const auto& [name, document] : outputs) { + const auto bytes = Document::to_bson(document); + std::ofstream out(stage_dir / name, std::ios::binary | std::ios::trunc); + out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + if (!out.good()) { + TOAST_ERROR("Params", "Cannot write {}", (stage_dir / name).string()); + return false; + } + } + return true; +} + +} diff --git a/engine/src/toast/params/cook.hpp b/engine/src/toast/params/cook.hpp new file mode 100644 index 000000000..f131c3312 --- /dev/null +++ b/engine/src/toast/params/cook.hpp @@ -0,0 +1,19 @@ +/** + * @file cook.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Turns a project's config files into the BSON a + */ + +#pragma once +#include +#include + +namespace toast::params { + +TOAST_API auto cookConfigs( + const std::filesystem::path& config_dir, const std::filesystem::path& toast_file, const std::filesystem::path& stage_dir +) -> bool; + +} diff --git a/engine/src/toast/params/document.cpp b/engine/src/toast/params/document.cpp new file mode 100644 index 000000000..ec36981f6 --- /dev/null +++ b/engine/src/toast/params/document.cpp @@ -0,0 +1,105 @@ +#include "document.hpp" + +#include +#include + +namespace toast::params { +namespace { + +auto toJson(const toml::node& node) -> Document { + switch (node.type()) { + case toml::node_type::table: { + auto object = Document::object(); + for (const auto& [key, child] : *node.as_table()) { + object[std::string {key.str()}] = toJson(child); + } + return object; + } + case toml::node_type::array: { + auto array = Document::array(); + for (const auto& child : *node.as_array()) { + array.push_back(toJson(child)); + } + return array; + } + case toml::node_type::string: return node.as_string()->get(); + case toml::node_type::integer: return node.as_integer()->get(); + case toml::node_type::floating_point: return node.as_floating_point()->get(); + case toml::node_type::boolean: return node.as_boolean()->get(); + default: { + std::ostringstream text; + text << toml::toml_formatter {node}; + return text.str(); + } + } +} + +auto toTable(const Document& object) -> toml::table; +auto toArray(const Document& array) -> toml::array; + +void put(toml::table& table, const std::string& key, const Document& value) { + if (value.is_object()) { + table.insert_or_assign(key, toTable(value)); + } else if (value.is_array()) { + table.insert_or_assign(key, toArray(value)); + } else if (value.is_boolean()) { + table.insert_or_assign(key, value.get()); + } else if (value.is_number_integer()) { + table.insert_or_assign(key, value.get()); + } else if (value.is_number_float()) { + table.insert_or_assign(key, value.get()); + } else if (value.is_string()) { + table.insert_or_assign(key, value.get()); + } +} + +void push(toml::array& array, const Document& value) { + if (value.is_object()) { + array.push_back(toTable(value)); + } else if (value.is_array()) { + array.push_back(toArray(value)); + } else if (value.is_boolean()) { + array.push_back(value.get()); + } else if (value.is_number_integer()) { + array.push_back(value.get()); + } else if (value.is_number_float()) { + array.push_back(value.get()); + } else if (value.is_string()) { + array.push_back(value.get()); + } +} + +auto toTable(const Document& object) -> toml::table { + toml::table table; + for (const auto& [key, value] : object.items()) { + put(table, key, value); + } + return table; +} + +auto toArray(const Document& array) -> toml::array { + toml::array out; + for (const auto& value : array) { + push(out, value); + } + return out; +} + +} + +auto tomlToDocument(std::string_view text) -> std::expected { + try { + const toml::table table = toml::parse(text); + return toJson(table); + } catch (const toml::parse_error& error) { + return std::unexpected(std::string {error.description()}); + } catch (const std::exception& error) { return std::unexpected(std::string {error.what()}); } +} + +auto documentToToml(const Document& document) -> std::string { + std::ostringstream out; + out << toml::toml_formatter {toTable(document.is_object() ? document : Document::object())}; + return out.str(); +} + +} diff --git a/engine/src/toast/params/document.hpp b/engine/src/toast/params/document.hpp new file mode 100644 index 000000000..c6c16ba21 --- /dev/null +++ b/engine/src/toast/params/document.hpp @@ -0,0 +1,24 @@ +/** + * @file document.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief The common shape a config file has in memory + */ + +#pragma once +#include +#include +#include +#include +#include + +namespace toast::params { + +using Document = nlohmann::json; + +TOAST_API auto tomlToDocument(std::string_view text) -> std::expected; + +TOAST_API auto documentToToml(const Document& document) -> std::string; + +} diff --git a/engine/src/toast/params/files.cpp b/engine/src/toast/params/files.cpp new file mode 100644 index 000000000..82b762fb6 --- /dev/null +++ b/engine/src/toast/params/files.cpp @@ -0,0 +1,386 @@ +#include "files.hpp" + +#include "registry.hpp" + +#include +#include +#include +#include + +namespace toast::params { +namespace { + +auto tidy(double value) -> double { + const auto narrowed = static_cast(value); + if (static_cast(narrowed) != value) { + return value; + } + std::array buffer {}; + const auto written = std::to_chars(buffer.data(), buffer.data() + buffer.size(), narrowed); + double shortest = value; + std::from_chars(buffer.data(), written.ptr, shortest); + return shortest; +} + +auto scalarToJson(const Scalar& scalar) -> Document { + return std::visit( + [](const auto& v) -> Document { + using T = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) { + return v; + } else if constexpr (std::is_same_v) { + return tidy(v); + } else if constexpr (std::is_same_v) { + return Document::array({tidy(v.x), tidy(v.y)}); + } else if constexpr (std::is_same_v) { + return Document::array({tidy(v.x), tidy(v.y), tidy(v.z)}); + } else if constexpr (std::is_same_v || std::is_same_v) { + return Document::array({tidy(v.x), tidy(v.y), tidy(v.z), tidy(v.w)}); + } else { + return v.uri; + } + }, + scalar + ); +} + +auto valueToJson(const Value& value) -> Document { + if (const auto* scalar = std::get_if(&value)) { + return scalarToJson(*scalar); + } + auto array = Document::array(); + for (const auto& item : std::get>(value)) { + array.push_back(scalarToJson(item)); + } + return array; +} + +auto jsonComponents(const Document& node, size_t count) -> std::optional> { + if (!node.is_array() || node.size() != count) { + return std::nullopt; + } + std::array out {}; + for (size_t i = 0; i < count; ++i) { + if (!node[i].is_number()) { + return std::nullopt; + } + out[i] = node[i].get(); + } + return out; +} + +auto jsonToScalar(const Document& node, Type type) -> std::optional { + switch (type) { + case Type::boolean: return node.is_boolean() ? std::optional {node.get()} : std::nullopt; + case Type::integer: return node.is_number_integer() ? std::optional {node.get()} : std::nullopt; + case Type::floating: return node.is_number() ? std::optional {node.get()} : std::nullopt; + case Type::string: return node.is_string() ? std::optional {node.get()} : std::nullopt; + case Type::asset: return node.is_string() ? std::optional {AssetRef {node.get()}} : std::nullopt; + case Type::vec2: { + const auto c = jsonComponents(node, 2); + return c ? std::optional {glm::vec2 {(*c)[0], (*c)[1]}} : std::nullopt; + } + case Type::vec3: { + const auto c = jsonComponents(node, 3); + return c ? std::optional {glm::vec3 {(*c)[0], (*c)[1], (*c)[2]}} : std::nullopt; + } + case Type::vec4: { + const auto c = jsonComponents(node, 4); + return c ? std::optional {glm::vec4 {(*c)[0], (*c)[1], (*c)[2], (*c)[3]}} : std::nullopt; + } + case Type::quat: { + const auto c = jsonComponents(node, 4); + return c ? std::optional {glm::quat {(*c)[3], (*c)[0], (*c)[1], (*c)[2]}} : std::nullopt; + } + } + return std::nullopt; +} + +auto jsonToValue(const Document& node, Type type, bool is_array) -> std::optional { + if (!is_array) { + auto scalar = jsonToScalar(node, type); + return scalar ? std::optional {Value {std::move(*scalar)}} : std::nullopt; + } + if (!node.is_array()) { + return std::nullopt; + } + std::vector items; + items.reserve(node.size()); + for (const auto& element : node) { + auto scalar = jsonToScalar(element, type); + if (!scalar) { + return std::nullopt; + } + items.push_back(std::move(*scalar)); + } + return Value {std::move(items)}; +} + +auto splitId(std::string_view id) -> std::vector { + std::vector parts; + size_t start = 0; + while (true) { + const size_t dot = id.find('.', start); + if (dot == std::string_view::npos) { + parts.emplace_back(id.substr(start)); + return parts; + } + parts.emplace_back(id.substr(start, dot - start)); + start = dot + 1; + } +} + +auto findNode(const Document& document, std::string_view id) -> const Document* { + const Document* current = &document; + for (const auto& part : splitId(id)) { + if (!current->is_object()) { + return nullptr; + } + const auto it = current->find(part); + if (it == current->end()) { + return nullptr; + } + current = &*it; + } + return current; +} + +void setNode(Document& document, std::string_view id, Document value) { + Document* current = &document; + const auto parts = splitId(id); + for (size_t i = 0; i + 1 < parts.size(); ++i) { + Document& child = (*current)[parts[i]]; + if (!child.is_object()) { + child = Document::object(); + } + current = &child; + } + (*current)[parts.back()] = std::move(value); +} + +void eraseNode(Document& document, std::string_view id) { + const auto parts = splitId(id); + std::vector chain {&document}; + for (size_t i = 0; i + 1 < parts.size(); ++i) { + Document* current = chain.back(); + const auto it = current->find(parts[i]); + if (!current->is_object() || it == current->end() || !it->is_object()) { + return; + } + chain.push_back(&*it); + } + chain.back()->erase(parts.back()); + for (size_t i = chain.size() - 1; i > 0; --i) { + if (!chain[i]->empty()) { + break; + } + chain[i - 1]->erase(parts[i - 1]); + } +} + +} + +static auto bsonToResult(const std::string& bytes) -> ReadResult { + try { + auto document = Document::from_bson(std::string_view {bytes}); + if (!document.is_object()) { + return {ReadStatus::corrupt, Document::object(), "not a document"}; + } + return {ReadStatus::ok, std::move(document), {}}; + } catch (const std::exception& error) { return {ReadStatus::corrupt, Document::object(), error.what()}; } +} + +namespace { + +auto readAll(const std::filesystem::path& path) -> std::string { + std::ifstream in(path, std::ios::binary); + std::stringstream buffer; + buffer << in.rdbuf(); + return buffer.str(); +} + +} + +DirectoryConfigSource::DirectoryConfigSource(std::filesystem::path directory, ConfigFormat format) + : m_directory(std::move(directory)), + m_format(format) { } + +auto DirectoryConfigSource::pathFor(std::string_view group) const -> std::filesystem::path { + return m_directory / (std::string {group} + (m_format == ConfigFormat::toml ? ".toml" : ".bson")); +} + +auto DirectoryConfigSource::read(std::string_view group) const -> ReadResult { + const auto path = pathFor(group); + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { + return {}; + } + if (m_format == ConfigFormat::bson) { + return bsonToResult(readAll(path)); + } + auto parsed = tomlToDocument(readAll(path)); + if (!parsed) { + return {ReadStatus::corrupt, Document::object(), parsed.error()}; + } + return {ReadStatus::ok, std::move(*parsed), {}}; +} + +auto DirectoryConfigSource::write(std::string_view group, const Document& document) -> bool { + const auto path = pathFor(group); + std::error_code ec; + std::filesystem::create_directories(m_directory, ec); + + if (read(group).status == ReadStatus::corrupt) { + auto backup = path; + backup += ".bak"; + std::filesystem::copy_file(path, backup, std::filesystem::copy_options::overwrite_existing, ec); + TOAST_WARN("Params", "{} could not be read; kept as {}", path.string(), backup.string()); + } + + auto temporary = path; + temporary += ".tmp"; + { + std::ofstream out(temporary, std::ios::binary | std::ios::trunc); + if (!out) { + return false; + } + if (m_format == ConfigFormat::bson) { + const auto bytes = Document::to_bson(document); + out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + } else { + out << documentToToml(document); + } + if (!out.good()) { + return false; + } + } + std::filesystem::rename(temporary, path, ec); + return !ec; +} + +Files::Files(std::unique_ptr project, std::unique_ptr saved) + : m_project(std::move(project)), + m_saved(std::move(saved)) { } + +auto Files::source(Layer layer) const -> ConfigSource* { + switch (layer) { + case Layer::project: return m_project.get(); + case Layer::saved: return m_saved.get(); + default: return nullptr; + } +} + +void Files::load(GroupBase& group, bool keep_unsaved) { + for (const Layer layer : {Layer::project, Layer::saved}) { + ConfigSource* src = source(layer); + if (src == nullptr || (keep_unsaved && group.dirty(layer))) { + continue; + } + + auto result = src->read(group.name()); + if (result.status == ReadStatus::corrupt) { + TOAST_ERROR("Params", "'{}' could not be read ({}); using defaults for it", group.name(), result.error); + } + Document document = + result.status == ReadStatus::ok && result.document.is_object() ? std::move(result.document) : Document::object(); + + for (ParamBase* param : group.params()) { + if (layer == Layer::project && param->kind() == Kind::user) { + continue; + } + const Document* node = findNode(document, param->id()); + if (node == nullptr) { + if (param->layerValue(layer).has_value()) { + param->setLayer(layer, std::nullopt); + } + continue; + } + auto value = jsonToValue(*node, param->type(), param->isArray()); + if (!value || !param->accepts(*value)) { + if (m_reported.insert(std::string {group.name()} + "." + std::string {param->id()}).second) { + TOAST_WARN( + "Params", + "'{}.{}' in the {} file is not a valid value; keeping the default", + group.name(), + param->id(), + layer == Layer::project ? "project" : "saved" + ); + } + param->setLayer(layer, std::nullopt); + continue; + } + param->setLayer(layer, std::move(value)); + } + + m_documents[{std::string {group.name()}, layer}] = std::move(document); + group.clearDirty(layer); + } +} + +auto Files::save(GroupBase& group, Layer layer) -> bool { + ConfigSource* src = source(layer); + if (src == nullptr) { + return false; + } + + const auto key = std::make_pair(std::string {group.name()}, layer); + Document document = Document::object(); + if (const auto it = m_documents.find(key); it != m_documents.end()) { + document = it->second; + } + + for (ParamBase* param : group.params()) { + const bool is_user = param->kind() == Kind::user; + if (layer == Layer::project && is_user) { + continue; + } + + const auto& stored = param->layerValue(layer); + const Document* existing = findNode(document, param->id()); + + Document below = valueToJson(param->defaultValue()); + if (layer == Layer::saved && !is_user) { + if (const auto& project_value = param->layerValue(Layer::project); project_value && param->accepts(*project_value)) { + below = valueToJson(*project_value); + } + } + + if (stored.has_value() && param->accepts(*stored)) { + Document written = valueToJson(*stored); + if (written != below) { + setNode(document, param->id(), std::move(written)); + } else if (existing != nullptr) { + eraseNode(document, param->id()); + } + } else if (!stored.has_value() && existing != nullptr && jsonToValue(*existing, param->type(), param->isArray())) { + eraseNode(document, param->id()); + } + } + + if (!src->write(group.name(), document)) { + TOAST_ERROR("Params", "Could not write the {} file of '{}'", layer == Layer::project ? "project" : "saved", group.name()); + return false; + } + m_documents[key] = std::move(document); + group.clearDirty(layer); + return true; +} + +auto Files::saveDirty() -> size_t { + size_t written = 0; + for (const auto& entry : Registry::get().dirtyGroups()) { + if (save(*entry.group, entry.layer)) { + ++written; + } + } + return written; +} + +void Files::reload() { + Registry::get().clearRuntime(); + for (GroupBase* group : Registry::get().groups()) { + load(*group, true); + } +} + +} diff --git a/engine/src/toast/params/files.hpp b/engine/src/toast/params/files.hpp new file mode 100644 index 000000000..31319fdad --- /dev/null +++ b/engine/src/toast/params/files.hpp @@ -0,0 +1,95 @@ +/** + * @file files.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Reads and writes a group's layers + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::params { + +enum class ReadStatus : uint8_t { + missing, + corrupt, + ok +}; + +struct ReadResult { + ReadStatus status = ReadStatus::missing; + Document document; + std::string error; +}; + +enum class ConfigFormat : uint8_t { + toml, + bson +}; + +class TOAST_API ConfigSource { +public: + virtual ~ConfigSource() = default; + + [[nodiscard]] + virtual auto read(std::string_view group) const -> ReadResult = 0; + + virtual auto write(std::string_view group, const Document& document) -> bool = 0; +}; + +class TOAST_API DirectoryConfigSource final : public ConfigSource { +public: + explicit DirectoryConfigSource(std::filesystem::path directory, ConfigFormat format = ConfigFormat::toml); + + [[nodiscard]] + auto read(std::string_view group) const -> ReadResult override; + + auto write(std::string_view group, const Document& document) -> bool override; + + [[nodiscard]] + auto directory() const -> const std::filesystem::path& { + return m_directory; + } + +private: + [[nodiscard]] + auto pathFor(std::string_view group) const -> std::filesystem::path; + + std::filesystem::path m_directory; + ConfigFormat m_format; +}; + +class TOAST_API Files { +public: + Files(std::unique_ptr project, std::unique_ptr saved); + + void load(GroupBase& group, bool keep_unsaved = false); + + auto save(GroupBase& group, Layer layer) -> bool; + + auto saveDirty() -> size_t; + + void reload(); + +private: + [[nodiscard]] + auto source(Layer layer) const -> ConfigSource*; + + std::unique_ptr m_project; + std::unique_ptr m_saved; + std::map, Document> m_documents; + std::set m_reported; +}; + +} diff --git a/engine/src/toast/params/group.cpp b/engine/src/toast/params/group.cpp new file mode 100644 index 000000000..7f90b6d42 --- /dev/null +++ b/engine/src/toast/params/group.cpp @@ -0,0 +1,174 @@ +#include "group.hpp" + +#include +#include +#include +#include +#include +#include + +namespace toast::params { +namespace { + +struct PrefixRange { + uintptr_t start; + size_t size; + std::string prefix; +}; + +struct Directory { + std::mutex mutex; + std::map groups; + std::vector order; + std::vector prefixes; +}; + +auto directory() -> Directory& { + static Directory instance; + return instance; +} + +} + +namespace detail { + +void addPrefix(const void* start, size_t size, std::string_view prefix) { + auto& dir = directory(); + const std::lock_guard lock(dir.mutex); + dir.prefixes.push_back({reinterpret_cast(start), size, std::string {prefix}}); +} + +void removePrefix(const void* start) { + auto& dir = directory(); + const std::lock_guard lock(dir.mutex); + std::erase_if(dir.prefixes, [start](const PrefixRange& range) { return range.start == reinterpret_cast(start); }); +} + +auto locateGroup(const void* address) -> GroupBase* { + auto& dir = directory(); + const std::lock_guard lock(dir.mutex); + const auto at = reinterpret_cast(address); + auto it = dir.groups.upper_bound(at); + if (it == dir.groups.begin()) { + return nullptr; + } + return std::prev(it)->second; +} + +auto prefixFor(const void* address) -> std::string { + auto& dir = directory(); + const std::lock_guard lock(dir.mutex); + const auto at = reinterpret_cast(address); + + std::vector containing; + for (const auto& range : dir.prefixes) { + if (at >= range.start && at < range.start + range.size) { + containing.push_back(&range); + } + } + std::ranges::sort(containing, [](const PrefixRange* a, const PrefixRange* b) { return a->size > b->size; }); + + std::string result; + for (const auto* range : containing) { + if (!result.empty()) { + result += '.'; + } + result += range->prefix; + } + return result; +} + +auto liveGroups() -> std::vector { + auto& dir = directory(); + const std::lock_guard lock(dir.mutex); + return dir.order; +} + +} + +GroupBase::GroupBase(std::string_view name) : m_name(name) { + auto& dir = directory(); + const std::lock_guard lock(dir.mutex); + for (const GroupBase* other : dir.order) { + if (other->name() == name) { + TOAST_WARN("Params", "A second group named '{}' is live; lookups by name find the first", name); + break; + } + } + dir.groups.emplace(reinterpret_cast(this), this); + dir.order.push_back(this); +} + +GroupBase::~GroupBase() { + auto& dir = directory(); + const std::lock_guard lock(dir.mutex); + dir.groups.erase(reinterpret_cast(this)); + std::erase(dir.order, this); +} + +auto GroupBase::find(std::string_view id) const -> ParamBase* { + const auto it = m_by_hash.find(fnv1a(id)); + if (it == m_by_hash.end() || it->second->id() != id) { + return nullptr; + } + return it->second; +} + +auto GroupBase::operator[](std::string_view id) const -> ParamBase& { + ParamBase* param = find(id); + if (param == nullptr) { + throw std::out_of_range(std::string {"no parameter '"} + std::string {id} + "' in group '" + std::string {m_name} + "'"); + } + return *param; +} + +auto GroupBase::findByAnchor(const void* anchor) const -> ParamBase* { + const auto it = m_by_anchor.find(anchor); + return it == m_by_anchor.end() ? nullptr : it->second; +} + +void GroupBase::adopt(std::unique_ptr param) { + m_owned.push_back(std::move(param)); +} + +namespace detail { + +void adopt(const void* anchor, std::unique_ptr param) { + if (GroupBase* group = locateGroup(anchor)) { + group->adopt(std::move(param)); + } else { + TOAST_ERROR("Params", "'{}' is not declared inside a Group and was dropped", param->id()); + } +} + +auto paramAt(const void* anchor) -> ParamBase* { + GroupBase* group = locateGroup(anchor); + ParamBase* param = group != nullptr ? group->findByAnchor(anchor) : nullptr; + if (param == nullptr) { + throw std::out_of_range("of(): the address is not a declared parameter"); + } + return param; +} + +} + +auto GroupBase::add(ParamBase& param) -> bool { + if (m_by_hash.contains(param.hash())) { + TOAST_ERROR("Params", "Duplicate parameter id '{}' in group '{}'; the first declaration is kept", param.id(), m_name); + return false; + } + m_by_hash.emplace(param.hash(), ¶m); + m_by_anchor.emplace(param.anchor(), ¶m); + m_params.push_back(¶m); + return true; +} + +void GroupBase::remove(ParamBase& param) { + if (const auto it = m_by_hash.find(param.hash()); it != m_by_hash.end() && it->second == ¶m) { + m_by_hash.erase(it); + m_by_anchor.erase(param.anchor()); + std::erase(m_params, ¶m); + } +} + +} diff --git a/engine/src/toast/params/group.hpp b/engine/src/toast/params/group.hpp new file mode 100644 index 000000000..de1277f00 --- /dev/null +++ b/engine/src/toast/params/group.hpp @@ -0,0 +1,131 @@ +/** + * @file group.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief A named set of parameters declared as the members + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::params { + +template +struct FixedString { + char value[N]; // NOLINT(modernize-avoid-c-arrays) + + constexpr FixedString(const char (&literal)[N]) { // NOLINT(google-explicit-constructor, modernize-avoid-c-arrays) + std::copy_n(literal, N, value); + } + + constexpr operator std::string_view() const { // NOLINT(google-explicit-constructor) + return {value, N - 1}; + } +}; + +namespace detail { + +TOAST_API void addPrefix(const void* start, size_t size, std::string_view prefix); +TOAST_API void removePrefix(const void* start); + +auto locateGroup(const void* address) -> GroupBase*; + +auto prefixFor(const void* address) -> std::string; + +auto liveGroups() -> std::vector; + +} + +class TOAST_API GroupBase { +public: + GroupBase(const GroupBase&) = delete; + GroupBase(GroupBase&&) = delete; + auto operator=(const GroupBase&) -> GroupBase& = delete; + auto operator=(GroupBase&&) -> GroupBase& = delete; + + [[nodiscard]] + auto name() const -> std::string_view { + return m_name; + } + + [[nodiscard]] + auto params() const -> std::span { + return m_params; + } + + [[nodiscard]] + auto find(std::string_view id) const -> ParamBase*; + + auto operator[](std::string_view id) const -> ParamBase&; + + [[nodiscard]] + auto findByAnchor(const void* anchor) const -> ParamBase*; + + void adopt(std::unique_ptr param); + + [[nodiscard]] + auto dirty(Layer layer) const -> bool { + return (m_dirty & (1U << static_cast(layer))) != 0; + } + + void markDirty(Layer layer) { m_dirty = static_cast(m_dirty | (1U << static_cast(layer))); } + + void clearDirty(Layer layer) { m_dirty = static_cast(m_dirty & ~(1U << static_cast(layer))); } + +protected: + explicit GroupBase(std::string_view name); + ~GroupBase(); + + /// Declares a plain field of the derived group as a parameter; see toast::params::declare + template + static auto param(T* self, Id id, std::type_identity_t default_value, const Meta>& meta = {}) -> T { + return declare(self, id, std::move(default_value), meta); + } + +private: + friend class ParamBase; + + auto add(ParamBase& param) -> bool; + void remove(ParamBase& param); + + std::string_view m_name; + uint8_t m_dirty = 0; + std::vector m_params; + std::unordered_map m_by_hash; + std::unordered_map m_by_anchor; + std::vector> m_owned; // last, so it is destroyed while the indexes above are alive +}; + +template +class Group : public GroupBase { +protected: + Group() : GroupBase(std::string_view {Name}) { } + + ~Group() = default; +}; + +template +class Sub { +protected: + Sub() { detail::addPrefix(this, sizeof(Derived), std::string_view {Prefix}); } + + ~Sub() { detail::removePrefix(this); } + +public: + Sub(const Sub&) = delete; + Sub(Sub&&) = delete; + auto operator=(const Sub&) -> Sub& = delete; + auto operator=(Sub&&) -> Sub& = delete; +}; + +} diff --git a/engine/src/toast/params/id.hpp b/engine/src/toast/params/id.hpp new file mode 100644 index 000000000..3965025fa --- /dev/null +++ b/engine/src/toast/params/id.hpp @@ -0,0 +1,35 @@ +/** + * @file id.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Compile-time hashed parameter ids + */ + +#pragma once +#include +#include +#include + +namespace toast::params { + +constexpr auto fnv1a(std::string_view text) noexcept -> uint64_t { + uint64_t hash = 14695981039346656037ULL; + for (const char c : text) { + hash ^= static_cast(c); + hash *= 1099511628211ULL; + } + return hash; +} + +struct Id { + std::string_view text; + uint64_t hash; + + template + // NOLINTNEXTLINE(google-explicit-constructor, modernize-avoid-c-arrays) + consteval Id(const char (&literal)[N]) : text(literal, N - 1), + hash(fnv1a(text)) { } +}; + +} diff --git a/engine/src/toast/params/migrate.cpp b/engine/src/toast/params/migrate.cpp new file mode 100644 index 000000000..d7140953f --- /dev/null +++ b/engine/src/toast/params/migrate.cpp @@ -0,0 +1,256 @@ +#include "migrate.hpp" + +#include "files.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::params { +namespace { + +auto readAll(const std::filesystem::path& path) -> std::string { + std::ifstream in(path, std::ios::binary); + std::stringstream buffer; + buffer << in.rdbuf(); + return buffer.str(); +} + +void mergeMissing(Document& target, const Document& source) { + for (const auto& [key, value] : source.items()) { + const auto it = target.find(key); + if (it == target.end()) { + target[key] = value; + } else if (it->is_object() && value.is_object()) { + mergeMissing(*it, value); + } + } +} + +auto writeGroups(const std::filesystem::path& directory, const std::map& groups) -> bool { + DirectoryConfigSource out {directory}; + bool ok = true; + for (const auto& [group, moved] : groups) { + Document merged = moved; + if (auto existing = out.read(group); existing.status == ReadStatus::ok) { + merged = std::move(existing.document); + mergeMissing(merged, moved); + } + ok = out.write(group, merged) && ok; + } + return ok; +} + +auto relocate( + Document& doc, std::string_view from_table, std::string_view key, std::string_view to_table, std::string_view to_key +) -> bool { + const auto from = doc.find(from_table); + if (from == doc.end() || !from->is_object() || !from->contains(key)) { + return false; + } + Document& table = doc[std::string {to_table}]; + if (!table.is_object()) { + table = Document::object(); + } + if (!table.contains(to_key)) { + table[std::string {to_key}] = (*from)[std::string {key}]; + } + from->erase(std::string {key}); + if (from->empty()) { + doc.erase(std::string {from_table}); + } + return true; +} + +auto joinComponents(Document& table, const std::string& name, std::array fallback) -> bool { + static constexpr std::array k_axes {"_x", "_y", "_z"}; + bool any = false; + std::array values = fallback; + for (size_t i = 0; i < 3; ++i) { + const std::string key = name + k_axes[i]; + if (const auto it = table.find(key); it != table.end()) { + any = true; + if (it->is_number()) { + values[i] = it->get(); + } + table.erase(key); + } + } + if (!any) { + return false; + } + if (!table.contains(name)) { + table[name] = Document::array({values[0], values[1], values[2]}); + } + return true; +} + +auto isLayerIndex(const std::string& key) -> bool { + return !key.empty() && std::ranges::all_of(key, [](unsigned char c) { return std::isdigit(c) != 0; }); +} + +auto upgradePhysics(Document& doc) -> bool { + bool changed = false; + + if (const auto layers = doc.find("layers"); layers != doc.end() && layers->is_object()) { + std::vector numbered; + for (const auto& [key, value] : layers->items()) { + if (isLayerIndex(key) && value.is_object()) { + numbered.push_back(key); + } + } + if (!numbered.empty()) { + const bool had_names = layers->contains("names") && (*layers)["names"].is_array(); + const bool had_abbreviations = layers->contains("abbreviations") && (*layers)["abbreviations"].is_array(); + Document names = had_names ? (*layers)["names"] : Document(physics::defaultLayerNames()); + Document abbreviations = had_abbreviations ? (*layers)["abbreviations"] : Document(physics::defaultLayerAbbreviations()); + for (const auto& key : numbered) { + const size_t index = std::stoul(key); + const Document& layer = (*layers)[key]; + if (index < names.size() && !had_names && layer.contains("name") && layer["name"].is_string()) { + names[index] = layer["name"]; + } + if (index < abbreviations.size() && !had_abbreviations && layer.contains("abbr") && layer["abbr"].is_string()) { + abbreviations[index] = layer["abbr"]; + } + layers->erase(key); + } + (*layers)["names"] = std::move(names); + (*layers)["abbreviations"] = std::move(abbreviations); + changed = true; + } + } + + if (const auto world = doc.find("world"); world != doc.end() && world->is_object()) { + changed = joinComponents(*world, "gravity", {0.0, 0.0, -9.8}) || changed; + changed = joinComponents(*world, "wind", {0.0, 0.0, 0.0}) || changed; + } + + changed = relocate(doc, "debug", "time_narrow_pairs", "step", "time_narrow_pairs") || changed; + changed = relocate(doc, "debug", "draw_shapes", "world", "draw_shapes") || changed; + changed = relocate(doc, "debug", "draw_bounds", "broadphase", "draw_bounds") || changed; + changed = relocate(doc, "debug", "draw_contacts", "solver", "draw_contacts") || changed; + changed = relocate(doc, "debug", "draw_velocity", "world", "draw_velocity") || changed; + changed = relocate(doc, "debug", "draw_centers", "world", "draw_centers") || changed; + changed = relocate(doc, "debug", "velocity_scale", "world", "velocity_scale") || changed; + changed = relocate(doc, "debug", "normal_length", "solver", "contact_normal_length") || changed; + return changed; +} + +auto upgradeRenderer(Document& doc) -> bool { + bool changed = relocate(doc, "debug", "overlay_in_game", "display", "debug_overlay"); + changed = relocate(doc, "debug", "glass_cost_view", "voxels", "glass_cost_view") || changed; + return changed; +} + +} + +auto upgradeLegacyConfig(const std::filesystem::path& config_dir) -> bool { + DirectoryConfigSource source {config_dir}; + bool any = false; + const auto upgrade = [&](const char* group, bool (*fix)(Document&)) { + auto read = source.read(group); + if (read.status != ReadStatus::ok || !fix(read.document)) { + return; + } + if (source.write(group, read.document)) { + TOAST_INFO("Params", "Brought {}.toast in {} up to the current parameters", group, config_dir.string()); + any = true; + } + }; + upgrade("physics", upgradePhysics); + upgrade("renderer", upgradeRenderer); + return any; +} + +auto migrateProjectToast(const std::filesystem::path& toast_file, const std::filesystem::path& config_dir) -> bool { + std::error_code ec; + if (!std::filesystem::is_regular_file(toast_file, ec)) { + return false; + } + auto parsed = tomlToDocument(readAll(toast_file)); + if (!parsed) { + TOAST_WARN("Params", "{} could not be read, so it was not migrated: {}", toast_file.string(), parsed.error()); + return false; + } + + Document kept = Document::object(); + std::map groups; + for (const auto& [key, value] : parsed->items()) { + const bool top_level = key == "name" || key == "version"; + if (!top_level && (key == "databases" || key == "max_tick_rate")) { + groups.try_emplace("project", Document::object()).first->second[key] = value; + } else if (!top_level && value.is_object()) { + groups[key] = value; + } else { + kept[key] = value; + } + } + if (groups.empty()) { + return false; + } + + if (!writeGroups(config_dir, groups)) { + TOAST_ERROR( + "Params", "Could not write the config files in {}; {} was left as it was", config_dir.string(), toast_file.string() + ); + return false; + } + + { + auto temporary = toast_file; + temporary += ".tmp"; + std::ofstream out(temporary, std::ios::binary | std::ios::trunc); + out << documentToToml(kept); + out.close(); + std::filesystem::rename(temporary, toast_file, ec); + if (ec) { + TOAST_ERROR("Params", "Could not rewrite {}: {}", toast_file.string(), ec.message()); + return false; + } + } + TOAST_INFO("Params", "Moved the settings in {} to {}", toast_file.string(), config_dir.string()); + return true; +} + +auto migrateLegacyUserSettings(const std::filesystem::path& old_file, const std::filesystem::path& saved_config_dir) -> bool { + std::error_code ec; + if (!std::filesystem::is_regular_file(old_file, ec)) { + return false; + } + auto parsed = tomlToDocument(readAll(old_file)); + if (!parsed) { + TOAST_WARN("Params", "{} could not be read, so it was not migrated: {}", old_file.string(), parsed.error()); + return false; + } + + std::map groups; + for (const auto& [key, value] : parsed->items()) { + if (value.is_object()) { + groups[key] = value; + } + } + if (!groups.empty() && !writeGroups(saved_config_dir, groups)) { + TOAST_ERROR( + "Params", "Could not write the config files in {}; {} was left as it was", saved_config_dir.string(), old_file.string() + ); + return false; + } + + auto migrated = old_file; + migrated += ".migrated"; + std::filesystem::rename(old_file, migrated, ec); + if (ec) { + TOAST_ERROR("Params", "Could not set {} aside: {}", old_file.string(), ec.message()); + return false; + } + return true; +} + +} diff --git a/engine/src/toast/params/migrate.hpp b/engine/src/toast/params/migrate.hpp new file mode 100644 index 000000000..943ac8ff7 --- /dev/null +++ b/engine/src/toast/params/migrate.hpp @@ -0,0 +1,22 @@ +/** + * @file migrate.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief One-time moves from the old settings layout to config + */ + +#pragma once +#include +#include + +namespace toast::params { + +TOAST_API auto migrateProjectToast(const std::filesystem::path& toast_file, const std::filesystem::path& config_dir) -> bool; + +TOAST_API auto upgradeLegacyConfig(const std::filesystem::path& config_dir) -> bool; + +TOAST_API auto migrateLegacyUserSettings(const std::filesystem::path& old_file, const std::filesystem::path& saved_config_dir) + -> bool; + +} diff --git a/engine/src/toast/params/pack_source.cpp b/engine/src/toast/params/pack_source.cpp new file mode 100644 index 000000000..1a44c0799 --- /dev/null +++ b/engine/src/toast/params/pack_source.cpp @@ -0,0 +1,46 @@ +#include "pack_source.hpp" + +#include "toast/assets/pack.hpp" + +#include + +namespace toast::params { + +PackConfigSource::PackConfigSource(const std::filesystem::path& pak) : m_archive(std::make_unique(pak)) { } + +PackConfigSource::~PackConfigSource() = default; + +auto PackConfigSource::read(std::string_view group) const -> ReadResult { + const auto bytes = m_archive->read(std::string {group} + ".bson"); + if (!bytes) { + return {}; + } + try { + auto document = Document::from_bson(*bytes); + if (!document.is_object()) { + return {ReadStatus::corrupt, Document::object(), "not a document"}; + } + return {ReadStatus::ok, std::move(document), {}}; + } catch (const std::exception& error) { return {ReadStatus::corrupt, Document::object(), error.what()}; } +} + +auto PackConfigSource::write(std::string_view /*group*/, const Document& /*document*/) -> bool { + return false; +} + +auto openProjectSource(const std::filesystem::path& config_dir, const std::filesystem::path& pak) + -> std::unique_ptr { + std::error_code ec; + if (!pak.empty() && std::filesystem::is_regular_file(pak, ec)) { + try { + return std::make_unique(pak); + } catch (const std::exception& error) { + TOAST_ERROR( + "Params", "{} is not a readable pack ({}); reading {} instead", pak.string(), error.what(), config_dir.string() + ); + } + } + return std::make_unique(config_dir); +} + +} diff --git a/engine/src/toast/params/pack_source.hpp b/engine/src/toast/params/pack_source.hpp new file mode 100644 index 000000000..cc2d36335 --- /dev/null +++ b/engine/src/toast/params/pack_source.hpp @@ -0,0 +1,41 @@ +/** + * @file pack_source.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief The committed config layer of a shipped game + */ + +#pragma once +#include +#include +#include +#include + +namespace assets { +class PackArchive; +} + +namespace toast::params { + +class TOAST_API PackConfigSource final : public ConfigSource { +public: + explicit PackConfigSource(const std::filesystem::path& pak); + ~PackConfigSource() override; + + PackConfigSource(const PackConfigSource&) = delete; + auto operator=(const PackConfigSource&) -> PackConfigSource& = delete; + + [[nodiscard]] + auto read(std::string_view group) const -> ReadResult override; + + auto write(std::string_view group, const Document& document) -> bool override; + +private: + std::unique_ptr m_archive; +}; + +TOAST_API auto openProjectSource(const std::filesystem::path& config_dir, const std::filesystem::path& pak) + -> std::unique_ptr; + +} diff --git a/engine/src/toast/params/param.cpp b/engine/src/toast/params/param.cpp new file mode 100644 index 000000000..635c3fa28 --- /dev/null +++ b/engine/src/toast/params/param.cpp @@ -0,0 +1,93 @@ +#include "param.hpp" + +#include "group.hpp" +#include "registry.hpp" + +#include + +namespace toast::params { + +ParamBase::ParamBase(const Info& info) + : m_name(info.name), + m_description(info.description), + m_kind(info.kind), + m_options(info.options), + m_requires_restart(info.requires_restart), + m_asset_type(info.asset_type), + m_unit(info.unit) { + m_anchor = info.anchor != nullptr ? info.anchor : this; + const std::string prefix = detail::prefixFor(m_anchor); + if (prefix.empty()) { + m_id = std::string {info.id.text}; + m_hash = info.id.hash; + } else { + m_id = prefix + "." + std::string {info.id.text}; + m_hash = fnv1a(m_id); + } + + m_group = detail::locateGroup(m_anchor); + if (m_group != nullptr && !m_group->add(*this)) { + m_group = nullptr; + } +} + +ParamBase::~ParamBase() { + if (m_group != nullptr) { + m_group->remove(*this); + } +} + +void ParamBase::onChangeValue(std::function callback) { + m_callbacks.push_back(std::move(callback)); +} + +auto ParamBase::setLayer(Layer layer, std::optional value) -> bool { + const bool acceptable = !value.has_value() || accepts(*value); + m_layers[static_cast(layer)] = std::move(value); + resolve(); + return acceptable; +} + +void ParamBase::request(Value value, Layer layer) { + if (m_group == nullptr) { + TOAST_WARN("Params", "'{}' is not in a group so it cannot be requested", m_id); + return; + } + Registry::get().request(std::string {m_group->name()} + "." + m_id, std::move(value), layer); +} + +void ParamBase::resolve() { + constexpr std::array priority {Layer::runtime, Layer::saved, Layer::project}; + for (const Layer layer : priority) { + if (layer == Layer::project && m_kind == Kind::user) { + continue; + } + const auto& stored = m_layers[static_cast(layer)]; + if (stored.has_value() && apply(*stored)) { + return; + } + } + apply(defaultValue()); +} + +auto ParamBase::snapshot() const -> Value { + const std::lock_guard lock(m_snapshot_mutex); + return m_snapshot; +} + +void ParamBase::publish(Value current) { + const std::lock_guard lock(m_snapshot_mutex); + m_snapshot = std::move(current); +} + +void ParamBase::notify() { + if (m_callbacks.empty()) { + return; + } + const Value current = value(); + for (const auto& callback : m_callbacks) { + callback(current); + } +} + +} diff --git a/engine/src/toast/params/param.hpp b/engine/src/toast/params/param.hpp new file mode 100644 index 000000000..4309a10b8 --- /dev/null +++ b/engine/src/toast/params/param.hpp @@ -0,0 +1,398 @@ +/** + * @file param.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief One parameter + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::params { + +class GroupBase; + +template +struct Meta { + std::string_view name; + std::optional::Element> min; + std::optional::Element> max; + std::string_view unit; + Kind kind = Kind::normal; + std::string_view description; + std::span options; + bool requires_restart = false; + std::string_view asset_type; +}; + +class TOAST_API ParamBase { +public: + ParamBase(const ParamBase&) = delete; + ParamBase(ParamBase&&) = delete; + auto operator=(const ParamBase&) -> ParamBase& = delete; + auto operator=(ParamBase&&) -> ParamBase& = delete; + virtual ~ParamBase(); + + [[nodiscard]] + auto id() const -> std::string_view { + return m_id; + } + + [[nodiscard]] + auto hash() const -> uint64_t { + return m_hash; + } + + [[nodiscard]] + auto name() const -> std::string_view { + return m_name.empty() ? std::string_view {m_id} : m_name; + } + + [[nodiscard]] + auto description() const -> std::string_view { + return m_description; + } + + [[nodiscard]] + auto kind() const -> Kind { + return m_kind; + } + + [[nodiscard]] + auto options() const -> std::span { + return m_options; + } + + [[nodiscard]] + auto requiresRestart() const -> bool { + return m_requires_restart; + } + + [[nodiscard]] + auto assetType() const -> std::string_view { + return m_asset_type; + } + + [[nodiscard]] + auto unit() const -> std::string_view { + return m_unit; + } + + [[nodiscard]] + auto group() const -> GroupBase* { + return m_group; + } + + [[nodiscard]] + auto anchor() const -> const void* { + return m_anchor; + } + + [[nodiscard]] + virtual auto type() const -> Type = 0; + + [[nodiscard]] + virtual auto isArray() const -> bool = 0; + + [[nodiscard]] + virtual auto value() const -> Value = 0; + + [[nodiscard]] + auto snapshot() const -> Value; + + [[nodiscard]] + virtual auto defaultValue() const -> Value = 0; + + [[nodiscard]] + virtual auto minValue() const -> std::optional = 0; + + [[nodiscard]] + virtual auto maxValue() const -> std::optional = 0; + + virtual auto apply(const Value& value) -> bool = 0; + + [[nodiscard]] + virtual auto accepts(const Value& value) const -> bool = 0; + + auto setLayer(Layer layer, std::optional value) -> bool; + + [[nodiscard]] + auto layerValue(Layer layer) const -> const std::optional& { + return m_layers[static_cast(layer)]; + } + + void request(Value value, Layer layer = Layer::runtime); + + void onChangeValue(std::function callback); + +protected: + struct Info { + Id id; + std::string_view name; + std::string_view description; + Kind kind = Kind::normal; + std::span options; + bool requires_restart = false; + std::string_view asset_type; + std::string_view unit; + const void* anchor = nullptr; + }; + + explicit ParamBase(const Info& info); + + void notify(); + + void publish(Value current); + +private: + friend class GroupBase; + + std::string m_id; + uint64_t m_hash = 0; + std::string_view m_name; + std::string_view m_description; + Kind m_kind = Kind::normal; + std::span m_options; + bool m_requires_restart = false; + std::string_view m_asset_type; + std::string_view m_unit; + GroupBase* m_group = nullptr; + const void* m_anchor = nullptr; + std::array, k_layer_count> m_layers; + std::vector> m_callbacks; + mutable std::mutex m_snapshot_mutex; + Value m_snapshot; + + void resolve(); +}; + +namespace detail { + +template +concept FloatVector = !std::is_same_v && requires(E v) { + v.x; + v[0]; + E::length(); + requires std::is_floating_point_v; +}; + +template +void clampElement(E& value, const std::optional& min, const std::optional& max) { + if constexpr (std::is_arithmetic_v && !std::is_same_v) { + if (min && value < *min) { + value = *min; + } + if (max && value > *max) { + value = *max; + } + } else if constexpr (FloatVector) { + for (int i = 0; i < E::length(); ++i) { + if (min && value[i] < (*min)[i]) { + value[i] = (*min)[i]; + } + if (max && value[i] > (*max)[i]) { + value[i] = (*max)[i]; + } + } + } +} + +template +auto parseValue(const Value& value) -> std::optional { + using Element = typename Traits::Element; + if constexpr (std::is_integral_v && !std::is_same_v) { + const int64_t lowest = static_cast(std::numeric_limits::min()); + const int64_t highest = std::in_range(std::numeric_limits::max()) + ? static_cast(std::numeric_limits::max()) + : std::numeric_limits::max(); + const auto saturate = [lowest, highest](Scalar& scalar) { + if (auto* integer = std::get_if(&scalar)) { + *integer = std::clamp(*integer, lowest, highest); + } + }; + Value saturated = value; + if (auto* scalar = std::get_if(&saturated)) { + saturate(*scalar); + } else if (auto* items = std::get_if>(&saturated)) { + std::ranges::for_each(*items, saturate); + } + return fromValue(saturated); + } else { + return fromValue(value); + } +} + +template +auto isFinite(const E& value) -> bool { + if constexpr (std::is_floating_point_v) { + return std::isfinite(value); + } else if constexpr (requires { + value.x; + value[0]; + }) { + for (int i = 0; i < E::length(); ++i) { + if (!std::isfinite(value[i])) { + return false; + } + } + return true; + } else { + return true; + } +} + +template +auto isFiniteValue(const T& value) -> bool { + if constexpr (Traits::is_array) { + return std::ranges::all_of(value, [](const auto& element) { return isFinite(element); }); + } else { + return isFinite(value); + } +} + +} + +template +class Param final : public ParamBase { +public: + using Element = typename Traits::Element; + + Param(T* target, Id id, T default_value, const Meta& meta = {}) + : ParamBase( + Info { + id, meta.name, meta.description, meta.kind, meta.options, meta.requires_restart, meta.asset_type, meta.unit, target + } + ), + m_target(target), + m_default(std::move(default_value)), + m_meta(meta) { + publish(toValue(m_default)); + } + + [[nodiscard]] + auto get() const -> const T& { + return *m_target; + } + + void onChange(std::function callback) { + callback(*m_target); + onChangeValue([callback = std::move(callback)](const Value& v) { + if (auto typed = fromValue(v)) { + callback(*typed); + } + }); + } + + [[nodiscard]] + auto type() const -> Type override { + return Traits::type; + } + + [[nodiscard]] + auto isArray() const -> bool override { + return Traits::is_array; + } + + [[nodiscard]] + auto value() const -> Value override { + return toValue(*m_target); + } + + [[nodiscard]] + auto defaultValue() const -> Value override { + return toValue(m_default); + } + + [[nodiscard]] + auto minValue() const -> std::optional override { + return m_meta.min ? std::optional {Traits::toScalar(*m_meta.min)} : std::nullopt; + } + + [[nodiscard]] + auto maxValue() const -> std::optional override { + return m_meta.max ? std::optional {Traits::toScalar(*m_meta.max)} : std::nullopt; + } + + [[nodiscard]] + auto accepts(const Value& value) const -> bool override { + const auto parsed = detail::parseValue(value); + return parsed && detail::isFiniteValue(*parsed); + } + + void request(const T& value) { ParamBase::request(toValue(value)); } + + using ParamBase::request; + + auto apply(const Value& value) -> bool override { + auto parsed = detail::parseValue(value); + if (!parsed || !detail::isFiniteValue(*parsed)) { + return false; + } + if constexpr (Traits::is_array) { + for (auto& element : *parsed) { + detail::clampElement(element, m_meta.min, m_meta.max); + } + } else { + detail::clampElement(*parsed, m_meta.min, m_meta.max); + } + if (*parsed == *m_target) { + return true; + } + *m_target = std::move(*parsed); + publish(toValue(*m_target)); + notify(); + return true; + } + +private: + T* m_target; + T m_default; + Meta m_meta; +}; + +namespace detail { + +TOAST_API void adopt(const void* anchor, std::unique_ptr param); + +[[nodiscard]] +TOAST_API auto paramAt(const void* anchor) -> ParamBase*; + +} + +/// Registers `*self` (a plain field of a Group) as a parameter and returns its default so it can +/// initialise the field: `float gravity = param(&gravity, "world.gravity", -9.8f, {...});` +template +auto declare(T* self, Id id, std::type_identity_t default_value, const Meta>& meta = {}) -> T { + T initial = default_value; + detail::adopt(self, std::make_unique>(self, id, std::move(default_value), meta)); + return initial; +} + +/// The Param behind a field of a Group: `of(settings.gravity).request(...)` +template +auto of(const T& field) -> Param& { + return static_cast&>(*detail::paramAt(&field)); +} + +template +void onChange(const T& field, std::type_identity_t> callback) { + of(field).onChange(std::move(callback)); +} + +} diff --git a/engine/src/toast/params/params_ffi.cpp b/engine/src/toast/params/params_ffi.cpp new file mode 100644 index 000000000..883c0bcb8 --- /dev/null +++ b/engine/src/toast/params/params_ffi.cpp @@ -0,0 +1,519 @@ +#include "cook.hpp" +#include "registry.hpp" +#include "text.hpp" + +#include +#include +#include +#include + +namespace { + +using namespace toast::params; + +thread_local std::string g_string_return; +thread_local std::string g_error; + +constexpr auto k_write_wait = std::chrono::milliseconds(250); + +constexpr std::string_view k_layer_names = "physics.layers.names"; +constexpr std::string_view k_layer_abbreviations = "physics.layers.abbreviations"; + +struct Cached { + std::string path; + std::string label; + std::string category; + std::string description; +}; + +std::mutex g_cache_mutex; +std::unordered_map g_cache; + +auto titleCase(std::string text) -> std::string { + for (char& c : text) { + if (c == '_') { + c = ' '; + } + } + if (!text.empty()) { + text.front() = static_cast(std::toupper(static_cast(text.front()))); + } + return text; +} + +auto pathOf(const ParamBase& param) -> std::string { + return std::string {param.group()->name()} + "." + std::string {param.id()}; +} + +auto cachedFor(const ParamBase& param) -> const Cached& { + const std::lock_guard lock(g_cache_mutex); + auto path = pathOf(param); + auto it = g_cache.find(path); + if (it != g_cache.end()) { + return it->second; + } + const std::string_view id = param.id(); + const size_t dot = id.rfind('.'); + Cached cached; + cached.path = path; + cached.label = param.name(); + cached.category = titleCase(std::string {dot == std::string_view::npos ? param.group()->name() : id.substr(0, id.find('.'))}); + cached.description = param.description(); + return g_cache.emplace(std::move(path), std::move(cached)).first->second; +} + +auto allParams() -> std::vector { + std::vector all; + for (const GroupBase* group : Registry::get().groups()) { + for (ParamBase* param : group->params()) { + all.push_back(param); + } + } + return all; +} + +auto paramAt(int32_t index) -> ParamBase* { + if (index < 0) { + return nullptr; + } + const auto all = allParams(); + return static_cast(index) < all.size() ? all[static_cast(index)] : nullptr; +} + +auto ffiType(Type type) -> int32_t { + switch (type) { + case Type::boolean: return TOAST_SETTING_BOOL; + case Type::integer: return TOAST_SETTING_INT; + case Type::floating: return TOAST_SETTING_FLOAT; + case Type::string: + case Type::asset: return TOAST_SETTING_STRING; + case Type::vec2: return TOAST_SETTING_VEC2; + case Type::vec3: return TOAST_SETTING_VEC3; + case Type::vec4: return TOAST_SETTING_VEC4; + case Type::quat: return TOAST_SETTING_QUAT; + } + return TOAST_SETTING_STRING; +} + +auto drawableAsScalar(const ParamBase& param) -> bool { + if (param.isArray()) { + return false; + } + switch (param.type()) { + case Type::vec2: + case Type::vec3: + case Type::vec4: + case Type::quat: return false; + default: return true; + } +} + +auto toDouble(const std::optional& scalar) -> double { + if (!scalar) { + return 0.0; + } + if (const auto* d = std::get_if(&*scalar)) { + return *d; + } + if (const auto* i = std::get_if(&*scalar)) { + return static_cast(*i); + } + return 0.0; +} + +auto currentValue(const std::string& path) -> std::optional { + auto& registry = Registry::get(); + const ParamBase* param = registry.find(path); + if (param == nullptr) { + return std::nullopt; + } + if (auto pending = registry.pendingValue(path)) { + return pending; + } + return param->snapshot(); +} + +struct LayerKey { + std::string_view array; + size_t index; +}; + +auto parseLayerKey(std::string_view key) -> std::optional { + constexpr std::string_view k_prefix = "physics.layers."; + if (!key.starts_with(k_prefix)) { + return std::nullopt; + } + key.remove_prefix(k_prefix.size()); + const size_t dot = key.find('.'); + if (dot == std::string_view::npos || dot == 0) { + return std::nullopt; + } + size_t index = 0; + for (const char c : key.substr(0, dot)) { + if (c < '0' || c > '9') { + return std::nullopt; + } + index = (index * 10) + static_cast(c - '0'); + } + const std::string_view field = key.substr(dot + 1); + if (field == "name") { + return LayerKey {k_layer_names, index}; + } + if (field == "abbr") { + return LayerKey {k_layer_abbreviations, index}; + } + return std::nullopt; +} + +auto layerElement(const LayerKey& key) -> std::string { + const auto value = currentValue(std::string {key.array}); + if (!value) { + return {}; + } + const auto* items = std::get_if>(&*value); + if (items == nullptr || key.index >= items->size()) { + return {}; + } + const auto* text = std::get_if(&(*items)[key.index]); + return text != nullptr ? *text : std::string {}; +} + +auto authoringLayerFor(const ParamBase& param) -> Layer { + return param.kind() == Kind::user ? Layer::saved : Registry::get().authoringLayer(); +} + +void settle() { + Registry::get().waitForApply(k_write_wait); +} + +void writeLayerElement(const LayerKey& key, std::optional text) { + auto& registry = Registry::get(); + const ParamBase* param = registry.find(key.array); + if (param == nullptr) { + return; + } + std::vector items; + if (const auto current = currentValue(std::string {key.array}); + current && std::holds_alternative>(*current)) { + items = std::get>(*current); + } + const auto defaults = std::get>(param->defaultValue()); + if (items.size() < defaults.size()) { + items.insert(items.end(), defaults.begin() + static_cast(items.size()), defaults.end()); + } + if (key.index >= items.size()) { + return; + } + items[key.index] = text ? Scalar {*text} : defaults[key.index]; + registry.request(std::string {key.array}, Value {std::move(items)}, authoringLayerFor(*param)); + settle(); +} + +auto coerce(const ParamBase& param, Scalar input) -> std::optional { + if (param.isArray()) { + return std::nullopt; + } + switch (param.type()) { + case Type::boolean: + if (std::holds_alternative(input)) { + return Value {std::move(input)}; + } + break; + case Type::integer: + if (std::holds_alternative(input)) { + return Value {std::move(input)}; + } + break; + case Type::floating: + if (std::holds_alternative(input)) { + return Value {std::move(input)}; + } + if (const auto* integer = std::get_if(&input)) { + return Value {Scalar {static_cast(*integer)}}; + } + break; + case Type::string: + if (std::holds_alternative(input)) { + return Value {std::move(input)}; + } + break; + case Type::asset: + if (const auto* text = std::get_if(&input)) { + return Value {Scalar {AssetRef {*text}}}; + } + break; + default: break; + } + return std::nullopt; +} + +void write(const char* key, Scalar input) { + if (key == nullptr) { + return; + } + auto& registry = Registry::get(); + ParamBase* param = registry.find(key); + if (param == nullptr) { + return; + } + auto value = coerce(*param, std::move(input)); + if (!value || !param->accepts(*value)) { + return; + } + registry.request(key, std::move(*value), authoringLayerFor(*param)); + settle(); +} + +auto readScalar(const char* key) -> std::optional { + if (key == nullptr) { + return std::nullopt; + } + const auto value = currentValue(key); + if (!value) { + return std::nullopt; + } + if (const auto* scalar = std::get_if(&*value)) { + return *scalar; + } + return std::nullopt; +} + +} + +extern "C" { + +auto toast_settings_count() noexcept -> int32_t { + return static_cast(allParams().size()); +} + +auto toast_settings_get_desc(int32_t index, toast_setting_desc* out) noexcept -> int32_t { + const ParamBase* param = paramAt(index); + if (param == nullptr || out == nullptr) { + return 0; + } + const Cached& cached = cachedFor(*param); + + out->key = cached.path.c_str(); + out->label = cached.label.c_str(); + out->category = cached.category.c_str(); + out->description = cached.description.c_str(); + out->type = ffiType(param->type()); + out->min = toDouble(param->minValue()); + out->max = toDouble(param->maxValue()); + out->step = 0.0; + out->option_count = static_cast(param->options().size()); + out->requires_restart = param->requiresRestart() ? 1 : 0; + out->hidden = drawableAsScalar(*param) ? 0 : 1; + out->kind = static_cast(param->kind()); + out->is_array = param->isArray() ? 1 : 0; + out->value_type = static_cast(param->type()); + return 1; +} + +auto toast_settings_get_asset_type(int32_t index) noexcept -> const char* { + const ParamBase* param = paramAt(index); + if (param == nullptr || param->type() != Type::asset || param->isArray()) { + return ""; + } + return param->assetType().data() != nullptr ? param->assetType().data() : ""; +} + +auto toast_settings_get_unit(int32_t index) noexcept -> const char* { + const ParamBase* param = paramAt(index); + return param != nullptr && param->unit().data() != nullptr ? param->unit().data() : ""; +} + +auto toast_settings_get_option(int32_t index, int32_t option) noexcept -> const char* { + const ParamBase* param = paramAt(index); + if (param == nullptr || option < 0 || static_cast(option) >= param->options().size()) { + return nullptr; + } + return param->options()[static_cast(option)].data(); +} + +auto toast_settings_get_bool(const char* key) noexcept -> int32_t { + const auto scalar = readScalar(key); + const auto* typed = scalar ? std::get_if(&*scalar) : nullptr; + return typed != nullptr && *typed ? 1 : 0; +} + +auto toast_settings_get_int(const char* key) noexcept -> int64_t { + const auto scalar = readScalar(key); + const auto* typed = scalar ? std::get_if(&*scalar) : nullptr; + return typed != nullptr ? *typed : 0; +} + +auto toast_settings_get_float(const char* key) noexcept -> double { + const auto scalar = readScalar(key); + if (!scalar) { + return 0.0; + } + if (const auto* d = std::get_if(&*scalar)) { + return *d; + } + if (const auto* i = std::get_if(&*scalar)) { + return static_cast(*i); + } + return 0.0; +} + +auto toast_settings_get_string(const char* key) noexcept -> const char* { + g_string_return.clear(); + if (key != nullptr) { + if (const auto layer_key = parseLayerKey(key)) { + g_string_return = layerElement(*layer_key); + } else if (const auto scalar = readScalar(key)) { + if (const auto* text = std::get_if(&*scalar)) { + g_string_return = *text; + } else if (const auto* asset = std::get_if(&*scalar)) { + g_string_return = asset->uri; + } + } + } + return g_string_return.c_str(); +} + +auto toast_settings_get_text(const char* key) noexcept -> const char* { + g_string_return.clear(); + if (key != nullptr) { + const ParamBase* param = Registry::get().find(key); + if (const auto value = currentValue(key); param != nullptr && value) { + g_string_return = toText(*value, param->type(), param->options()); + } + } + return g_string_return.c_str(); +} + +auto toast_settings_get_default_text(const char* key) noexcept -> const char* { + g_string_return.clear(); + if (key != nullptr) { + if (const ParamBase* param = Registry::get().find(key); param != nullptr) { + g_string_return = toText(param->defaultValue(), param->type(), param->options()); + } + } + return g_string_return.c_str(); +} + +auto toast_settings_set_text(const char* key, const char* text) noexcept -> int32_t { + g_error.clear(); + if (key == nullptr || text == nullptr) { + g_error = "no key or no text"; + return 0; + } + auto& registry = Registry::get(); + ParamBase* param = registry.find(key); + if (param == nullptr) { + g_error = std::string {"no parameter '"} + key + "'"; + return 0; + } + auto value = fromText(text, param->type(), param->isArray(), param->options()); + if (!value) { + g_error = value.error(); + return 0; + } + if (!param->accepts(*value)) { + g_error = "that is not a value it can take"; + return 0; + } + registry.request(key, std::move(*value), authoringLayerFor(*param)); + settle(); + return 1; +} + +auto toast_settings_last_error() noexcept -> const char* { + return g_error.c_str(); +} + +auto toast_settings_is_overridden(const char* key) noexcept -> int32_t { + if (key == nullptr) { + return 0; + } + const ParamBase* param = Registry::get().find(key); + if (param == nullptr) { + return 0; + } + const auto current = currentValue(key); + if (!current) { + return 0; + } + return toText(*current, param->type(), param->options()) != toText(param->defaultValue(), param->type(), param->options()) ? 1 + : 0; +} + +void toast_settings_set_bool(const char* key, int32_t value) noexcept { + write(key, Scalar {value != 0}); +} + +void toast_settings_set_int(const char* key, int64_t value) noexcept { + write(key, Scalar {value}); +} + +void toast_settings_set_float(const char* key, double value) noexcept { + write(key, Scalar {value}); +} + +void toast_settings_set_string(const char* key, const char* value) noexcept { + if (key == nullptr || value == nullptr) { + return; + } + if (const auto layer_key = parseLayerKey(key)) { + writeLayerElement(*layer_key, std::string {value}); + return; + } + write(key, Scalar {std::string {value}}); +} + +void toast_settings_reset(const char* key) noexcept { + if (key == nullptr) { + return; + } + if (const auto layer_key = parseLayerKey(key)) { + writeLayerElement(*layer_key, std::nullopt); + return; + } + auto& registry = Registry::get(); + if (const ParamBase* param = registry.find(key); param != nullptr) { + registry.requestClear(key, authoringLayerFor(*param)); + settle(); + } +} + +void toast_settings_reset_all() noexcept { + auto& registry = Registry::get(); + for (const ParamBase* param : allParams()) { + const Layer layer = authoringLayerFor(*param); + if (param->layerValue(layer).has_value()) { + registry.requestClear(pathOf(*param), layer); + } + } + settle(); +} + +auto toast_settings_save() noexcept -> int32_t { + Registry::get().requestSave(); + return Registry::get().waitForApply(std::chrono::milliseconds(2000)) ? 1 : 0; +} + +auto toast_settings_is_dirty() noexcept -> int32_t { + return Registry::get().dirtyGroups().empty() ? 0 : 1; +} + +auto toast_settings_active_path() noexcept -> const char* { + g_string_return = Registry::get().layerPath(Registry::get().authoringLayer()); + return g_string_return.c_str(); +} + +void toast_settings_restore() noexcept { + Registry::get().requestRestore(); + Registry::get().waitForApply(std::chrono::milliseconds(2000)); +} + +auto toast_settings_cook(const char* config_dir, const char* toast_file, const char* stage_dir) noexcept -> int32_t { + if (config_dir == nullptr || toast_file == nullptr || stage_dir == nullptr) { + return 0; + } + try { + return cookConfigs(config_dir, toast_file, stage_dir) ? 1 : 0; + } catch (...) { return 0; } +} +} diff --git a/engine/src/toast/params/project_params.hpp b/engine/src/toast/params/project_params.hpp new file mode 100644 index 000000000..257aa4d0d --- /dev/null +++ b/engine/src/toast/params/project_params.hpp @@ -0,0 +1,63 @@ +/** + * @file project_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief The project level settings that used to live in + */ + +#pragma once +#include +#include +#include + +namespace toast::params { + +struct ProjectParams : Group<"project"> { + std::vector databases = param( + &databases, "databases", {"assets"}, + {.name = "Databases", .description = "Content folders; each one becomes a name:// root", .requires_restart = true} + ); + uint32_t max_tick_rate = param( + &max_tick_rate, "max_tick_rate", 500, + {.name = "Max tick rate", .unit = "Hz", .description = "Ticks per second in the editor and the player. 0 is uncapped"} + ); +}; + +struct GameplayParams : Group<"gameplay"> { + AssetRef init_scene = param( + &init_scene, "init_scene", AssetRef {}, + {.name = "Start scene", .description = "Loaded when the game starts", .asset_type = "node"} + ); + AssetRef player = param( + &player, "player", AssetRef {}, + {.name = "Player", .description = "Prefab spawned when the game starts", .asset_type = "node"} + ); +}; + +struct UIParams : Group<"ui"> { + AssetRef color_scheme = param( + &color_scheme, "color_scheme", AssetRef {}, + {.name = "Color scheme", .description = "Fallback for color formatting in the UI", .asset_type = "color_scheme"} + ); + float scale = param( + &scale, "scale", 1.0F, + {.name = "Interface scale", .min = 0.5F, .max = 3.0F, .description = "Makes the whole interface bigger or smaller"} + ); + float scroll_speed = param( + &scroll_speed, "scroll_speed", 1.0F, + {.name = "Scroll speed", .min = 0.1F, .max = 10.0F, .description = "How far the wheel scrolls lists"} + ); + std::vector languages = + param(&languages, "languages", {"en"}, {.name = "Languages", .description = "The first one is the default"}); + std::string language = param( + &language, "language", std::string {}, + {.name = "Language", + .kind = Kind::debug, + .description = + "The language the UI is showing right now. Set it from the console to preview another one; empty goes back to " + "the default"} + ); +}; + +} diff --git a/engine/src/toast/params/registry.cpp b/engine/src/toast/params/registry.cpp new file mode 100644 index 000000000..098b6b7a9 --- /dev/null +++ b/engine/src/toast/params/registry.cpp @@ -0,0 +1,192 @@ +#include "registry.hpp" + +#include +#include + +namespace toast::params { + +auto Registry::get() -> Registry& { + static Registry instance; + return instance; +} + +auto Registry::groups() const -> std::vector { + return detail::liveGroups(); +} + +auto Registry::findGroup(std::string_view name) const -> GroupBase* { + for (GroupBase* group : detail::liveGroups()) { + if (group->name() == name) { + return group; + } + } + return nullptr; +} + +auto Registry::find(std::string_view path) const -> ParamBase* { + const size_t dot = path.find('.'); + if (dot == std::string_view::npos) { + return nullptr; + } + const GroupBase* group = findGroup(path.substr(0, dot)); + return group != nullptr ? group->find(path.substr(dot + 1)) : nullptr; +} + +void Registry::request(std::string path, Value value, Layer layer) { + const std::lock_guard lock(m_mutex); + m_pending.push_back({std::move(path), std::move(value), layer}); +} + +void Registry::setSaveHandler(std::function handler) { + const std::lock_guard lock(m_mutex); + m_save_handler = std::move(handler); +} + +void Registry::setRestoreHandler(std::function handler) { + const std::lock_guard lock(m_mutex); + m_restore_handler = std::move(handler); +} + +void Registry::requestRestore() { + m_restore_requested = true; +} + +void Registry::requestSave() { + m_save_requested = true; +} + +void Registry::setLayerPath(Layer layer, std::string path) { + const std::lock_guard lock(m_mutex); + m_layer_paths[static_cast(layer)] = std::move(path); +} + +auto Registry::layerPath(Layer layer) const -> std::string { + const std::lock_guard lock(m_mutex); + return m_layer_paths[static_cast(layer)]; +} + +void Registry::requestClear(std::string path, Layer layer) { + const std::lock_guard lock(m_mutex); + m_pending.push_back({std::move(path), std::nullopt, layer}); +} + +auto Registry::pendingValue(std::string_view path) const -> std::optional { + const std::lock_guard lock(m_mutex); + for (const auto& entry : std::views::reverse(m_pending)) { + if (entry.path == path) { + return entry.value; + } + } + return std::nullopt; +} + +auto Registry::applyPending() -> size_t { + m_apply_thread = std::this_thread::get_id(); + ++m_passes_started; + + std::vector batch; + { + const std::lock_guard lock(m_mutex); + batch.swap(m_pending); + } + + size_t applied = 0; + for (auto& item : batch) { + ParamBase* param = find(item.path); + if (param == nullptr) { + if (m_reported.insert(item.path).second) { + TOAST_WARN("Params", "No parameter '{}'", item.path); + } + continue; + } + const Layer layer = param->kind() == Kind::user && item.layer == Layer::project ? Layer::saved : item.layer; + if (!param->setLayer(layer, std::move(item.value))) { + TOAST_WARN("Params", "'{}' does not take that value", item.path); + continue; + } + if (layer != Layer::runtime && param->group() != nullptr) { + param->group()->markDirty(layer); + } + ++applied; + } + + if (m_restore_requested.exchange(false)) { + std::function handler; + { + const std::lock_guard lock(m_mutex); + handler = m_restore_handler; + } + if (handler) { + handler(); + } + } + if (m_save_requested.exchange(false)) { + std::function handler; + { + const std::lock_guard lock(m_mutex); + handler = m_save_handler; + } + if (handler) { + handler(); + } + } + ++m_passes_finished; + return applied; +} + +auto Registry::waitForApply(std::chrono::milliseconds timeout) -> bool { + if (std::this_thread::get_id() == m_apply_thread.load()) { + applyPending(); + return true; + } + + const uint64_t wanted = m_passes_started.load() + 1; + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (m_passes_finished.load() < wanted) { + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return true; +} + +void Registry::setAuthoringLayer(Layer layer) { + m_authoring = layer == Layer::project ? Layer::project : Layer::saved; +} + +auto Registry::commit(ParamBase& param, Value value) -> bool { + if (!param.accepts(value)) { + return false; + } + const Layer layer = param.kind() == Kind::user ? Layer::saved : m_authoring; + param.setLayer(layer, std::move(value)); + if (param.group() != nullptr) { + param.group()->markDirty(layer); + } + return true; +} + +void Registry::clearRuntime() { + for (GroupBase* group : detail::liveGroups()) { + for (ParamBase* param : group->params()) { + if (param->layerValue(Layer::runtime).has_value()) { + param->setLayer(Layer::runtime, std::nullopt); + } + } + } +} + +auto Registry::dirtyGroups() const -> std::vector { + std::vector result; + for (GroupBase* group : detail::liveGroups()) { + for (const Layer layer : {Layer::project, Layer::saved}) { + if (group->dirty(layer)) { + result.push_back({group, layer}); + } + } + } + return result; +} + +} diff --git a/engine/src/toast/params/registry.hpp b/engine/src/toast/params/registry.hpp new file mode 100644 index 000000000..6b2cf6ab3 --- /dev/null +++ b/engine/src/toast/params/registry.hpp @@ -0,0 +1,104 @@ +/** + * @file registry.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Finds groups by name and moves writes from any + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::params { + +struct DirtyEntry { + GroupBase* group; + Layer layer; +}; + +class TOAST_API Registry { +public: + static auto get() -> Registry&; + + [[nodiscard]] + auto groups() const -> std::vector; + + [[nodiscard]] + auto findGroup(std::string_view name) const -> GroupBase*; + + [[nodiscard]] + auto find(std::string_view path) const -> ParamBase*; + + void request(std::string path, Value value, Layer layer = Layer::runtime); + + void requestClear(std::string path, Layer layer); + + [[nodiscard]] + auto pendingValue(std::string_view path) const -> std::optional; + + auto applyPending() -> size_t; + + void setSaveHandler(std::function handler); + + void requestSave(); + + void setRestoreHandler(std::function handler); + + void requestRestore(); + + void setLayerPath(Layer layer, std::string path); + + [[nodiscard]] + auto layerPath(Layer layer) const -> std::string; + + auto waitForApply(std::chrono::milliseconds timeout) -> bool; + + void setAuthoringLayer(Layer layer); + + [[nodiscard]] + auto authoringLayer() const -> Layer { + return m_authoring; + } + + auto commit(ParamBase& param, Value value) -> bool; + + void clearRuntime(); + + [[nodiscard]] + auto dirtyGroups() const -> std::vector; + +private: + struct Pending { + std::string path; + std::optional value; + Layer layer; + }; + + mutable std::mutex m_mutex; + std::vector m_pending; + std::unordered_set m_reported; + Layer m_authoring = Layer::saved; + std::function m_save_handler; + std::atomic m_save_requested {false}; + std::function m_restore_handler; + std::atomic m_restore_requested {false}; + std::array m_layer_paths; + std::atomic m_passes_started {0}; + std::atomic m_passes_finished {0}; + std::atomic m_apply_thread; +}; + +} diff --git a/engine/src/toast/params/text.cpp b/engine/src/toast/params/text.cpp new file mode 100644 index 000000000..3da185a09 --- /dev/null +++ b/engine/src/toast/params/text.cpp @@ -0,0 +1,296 @@ +#include "text.hpp" + +#include +#include +#include +#include +#include +#include + +namespace toast::params { +namespace { + +using Parsed = std::expected; + +auto trim(std::string_view text) -> std::string_view { + constexpr std::string_view k_space = " \t\r\n"; + const size_t first = text.find_first_not_of(k_space); + if (first == std::string_view::npos) { + return {}; + } + return text.substr(first, text.find_last_not_of(k_space) - first + 1); +} + +auto sameIgnoringCase(std::string_view a, std::string_view b) -> bool { + return std::ranges::equal(a, b, [](char x, char y) { + return std::tolower(static_cast(x)) == std::tolower(static_cast(y)); + }); +} + +auto parseDouble(std::string_view token) -> std::expected { + double value = 0.0; + const auto [end, error] = std::from_chars(token.data(), token.data() + token.size(), value); + if (token.empty() || error != std::errc {} || end != token.data() + token.size() || !std::isfinite(value)) { + return std::unexpected(std::format("expected a number, got '{}'", token)); + } + return value; +} + +auto parseInteger(std::string_view token, std::span options) -> Parsed { + for (size_t i = 0; i < options.size(); ++i) { + if (sameIgnoringCase(token, options[i])) { + return Scalar {static_cast(i)}; + } + } + + int64_t value = 0; + const auto [end, error] = std::from_chars(token.data(), token.data() + token.size(), value); + const bool is_number = !token.empty() && error == std::errc {} && end == token.data() + token.size(); + + if (options.empty()) { + if (!is_number) { + return std::unexpected(std::format("expected a whole number, got '{}'", token)); + } + return Scalar {value}; + } + + if (!is_number || value < 0 || static_cast(value) >= options.size()) { + std::string choices; + for (const auto& option : options) { + choices += choices.empty() ? "" : ", "; + choices += option; + } + return std::unexpected(std::format("'{}' is not one of: {}", token, choices)); + } + return Scalar {value}; +} + +auto parseComponents(std::string_view token, size_t count) -> std::expected, std::string> { + std::array out {}; + size_t found = 0; + size_t pos = 0; + while (true) { + pos = token.find_first_not_of(" \t", pos); + if (pos == std::string_view::npos) { + break; + } + const size_t end = token.find_first_of(" \t", pos); + const auto part = token.substr(pos, end == std::string_view::npos ? std::string_view::npos : end - pos); + auto number = parseDouble(part); + if (!number) { + return std::unexpected(number.error()); + } + if (found < out.size()) { + out[found] = static_cast(*number); + } + ++found; + if (end == std::string_view::npos) { + break; + } + pos = end; + } + if (found != count) { + return std::unexpected(std::format("expected {} numbers, got {}", count, found)); + } + return out; +} + +auto parseString(std::string_view token) -> Parsed { + if (token.empty() || token.front() != '"') { + return Scalar {std::string {token}}; + } + std::string out; + for (size_t i = 1; i < token.size(); ++i) { + const char c = token[i]; + if (c == '\\' && i + 1 < token.size() && (token[i + 1] == '"' || token[i + 1] == '\\')) { + out += token[++i]; + } else if (c == '"') { + if (i + 1 != token.size()) { + return std::unexpected("text after the closing quote"); + } + return Scalar {std::move(out)}; + } else { + out += c; + } + } + return std::unexpected("missing closing quote"); +} + +auto parseScalar(std::string_view raw, Type type, std::span options) -> Parsed { + const std::string_view token = trim(raw); + switch (type) { + case Type::boolean: + if (token == "true" || token == "on") { + return Scalar {true}; + } + if (token == "false" || token == "off") { + return Scalar {false}; + } + return std::unexpected(std::format("expected true, false, on or off, got '{}'", token)); + case Type::integer: return parseInteger(token, options); + case Type::floating: { + auto number = parseDouble(token); + if (!number) { + return std::unexpected(number.error()); + } + return Scalar {*number}; + } + case Type::string: return parseString(token); + case Type::vec2: + case Type::vec3: + case Type::vec4: + case Type::quat: { + size_t count = 4; + if (type == Type::vec2) { + count = 2; + } else if (type == Type::vec3) { + count = 3; + } + auto c = parseComponents(token, count); + if (!c) { + return std::unexpected(c.error()); + } + switch (type) { + case Type::vec2: + return Scalar { + glm::vec2 {(*c)[0], (*c)[1]} + }; + case Type::vec3: + return Scalar { + glm::vec3 {(*c)[0], (*c)[1], (*c)[2]} + }; + case Type::vec4: + return Scalar { + glm::vec4 {(*c)[0], (*c)[1], (*c)[2], (*c)[3]} + }; + default: + return Scalar { + glm::quat {(*c)[3], (*c)[0], (*c)[1], (*c)[2]} + }; + } + } + case Type::asset: + if (!token.empty() && (!token.contains("://") || token.contains(' '))) { + return std::unexpected(std::format("expected a URI like asset://name, got '{}'", token)); + } + return Scalar {AssetRef {std::string {token}}}; + } + return std::unexpected("unknown type"); +} + +auto splitElements(std::string_view text) -> std::vector { + std::vector parts; + size_t start = 0; + bool quoted = false; + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] == '\\' && quoted) { + ++i; + } else if (text[i] == '"') { + quoted = !quoted; + } else if (text[i] == ';' && !quoted) { + parts.push_back(text.substr(start, i - start)); + start = i + 1; + } + } + parts.push_back(text.substr(start)); + return parts; +} + +auto formatFloat(double value) -> std::string { + std::array buffer {}; + const auto narrowed = static_cast(value); + const auto result = static_cast(narrowed) == value + ? std::to_chars(buffer.data(), buffer.data() + buffer.size(), narrowed) + : std::to_chars(buffer.data(), buffer.data() + buffer.size(), value); + return {buffer.data(), result.ptr}; +} + +auto quote(const std::string& text) -> std::string { + std::string out = "\""; + for (const char c : text) { + if (c == '"' || c == '\\') { + out += '\\'; + } + out += c; + } + out += '"'; + return out; +} + +auto scalarToText(const Scalar& scalar, std::span options) -> std::string { + return std::visit( + [&](const auto& v) -> std::string { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return v ? "true" : "false"; + } else if constexpr (std::is_same_v) { + if (v >= 0 && static_cast(v) < options.size()) { + return std::string {options[static_cast(v)]}; + } + return std::to_string(v); + } else if constexpr (std::is_same_v) { + return formatFloat(v); + } else if constexpr (std::is_same_v) { + return quote(v); + } else if constexpr (std::is_same_v) { + return formatFloat(v.x) + " " + formatFloat(v.y); + } else if constexpr (std::is_same_v) { + return formatFloat(v.x) + " " + formatFloat(v.y) + " " + formatFloat(v.z); + } else if constexpr (std::is_same_v || std::is_same_v) { + return formatFloat(v.x) + " " + formatFloat(v.y) + " " + formatFloat(v.z) + " " + formatFloat(v.w); + } else { + return v.uri; + } + }, + scalar + ); +} + +} + +auto fromText(std::string_view text, Type type, bool is_array, std::span options) + -> std::expected { + if (!is_array) { + auto scalar = parseScalar(text, type, options); + if (!scalar) { + return std::unexpected(scalar.error()); + } + return Value {std::move(*scalar)}; + } + + std::vector items; + if (trim(text).empty()) { + return Value {std::move(items)}; + } + const auto parts = splitElements(text); + for (size_t i = 0; i < parts.size(); ++i) { + if (trim(parts[i]).empty()) { + return std::unexpected(std::format("element {} is empty", i + 1)); + } + auto scalar = parseScalar(parts[i], type, options); + if (!scalar) { + return std::unexpected(std::format("element {}: {}", i + 1, scalar.error())); + } + items.push_back(std::move(*scalar)); + } + return Value {std::move(items)}; +} + +auto toText(const Value& value, Type type, std::span options) -> std::string { + const auto choices = type == Type::integer ? options : std::span {}; + if (const auto* scalar = std::get_if(&value)) { + return scalarToText(*scalar, choices); + } + std::string out; + bool first = true; + for (const auto& item : std::get>(value)) { + if (!first) { + out += ';'; + } + first = false; + out += scalarToText(item, choices); + } + return out; +} + +} diff --git a/engine/src/toast/params/text.hpp b/engine/src/toast/params/text.hpp new file mode 100644 index 000000000..584bf3a75 --- /dev/null +++ b/engine/src/toast/params/text.hpp @@ -0,0 +1,24 @@ +/** + * @file text.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Values as the text a person types and reads + */ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace toast::params { + +TOAST_API auto fromText(std::string_view text, Type type, bool is_array, std::span options = {}) + -> std::expected; + +TOAST_API auto toText(const Value& value, Type type, std::span options = {}) -> std::string; + +} diff --git a/engine/src/toast/params/value.hpp b/engine/src/toast/params/value.hpp new file mode 100644 index 000000000..8689fdbf0 --- /dev/null +++ b/engine/src/toast/params/value.hpp @@ -0,0 +1,202 @@ +/** + * @file value.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Storage types of parameters and the mapping from C++ + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::params { + +enum class Type : uint8_t { + boolean, + integer, + floating, + string, + vec2, + vec3, + vec4, + quat, + asset +}; + +enum class Kind : uint8_t { + normal, + advanced, + debug, + user +}; + +enum class Layer : uint8_t { + project, + saved, + runtime +}; + +inline constexpr size_t k_layer_count = 3; + +struct AssetRef { + std::string uri; + + auto operator==(const AssetRef&) const -> bool = default; +}; + +using Scalar = std::variant; + +using Value = std::variant>; + +template +struct Traits; + +template<> +struct Traits { + static constexpr Type type = Type::boolean; + static constexpr bool is_array = false; + using Element = bool; + + static auto toScalar(const bool& v) -> Scalar { return Scalar {v}; } + + static auto fromScalar(const Scalar& s) -> std::optional { + if (const auto* v = std::get_if(&s)) { + return *v; + } + return std::nullopt; + } +}; + +template + requires(std::is_integral_v && !std::is_same_v) +struct Traits { + static constexpr Type type = Type::integer; + static constexpr bool is_array = false; + using Element = T; + + static auto toScalar(const T& v) -> Scalar { return Scalar {static_cast(v)}; } + + static auto fromScalar(const Scalar& s) -> std::optional { + if (const auto* v = std::get_if(&s); v != nullptr && std::in_range(*v)) { + return static_cast(*v); + } + return std::nullopt; + } +}; + +template + requires std::is_floating_point_v +struct Traits { + static constexpr Type type = Type::floating; + static constexpr bool is_array = false; + using Element = T; + + static auto toScalar(const T& v) -> Scalar { return Scalar {static_cast(v)}; } + + static auto fromScalar(const Scalar& s) -> std::optional { + if (const auto* d = std::get_if(&s)) { + return static_cast(*d); + } + if (const auto* i = std::get_if(&s)) { + return static_cast(*i); + } + return std::nullopt; + } +}; + +namespace detail { + +template +struct DirectTraits { + static constexpr Type type = kType; + static constexpr bool is_array = false; + using Element = T; + + static auto toScalar(const T& v) -> Scalar { return Scalar {v}; } + + static auto fromScalar(const Scalar& s) -> std::optional { + if (const auto* v = std::get_if(&s)) { + return *v; + } + return std::nullopt; + } +}; + +} + +template<> +struct Traits : detail::DirectTraits { }; + +template<> +struct Traits : detail::DirectTraits { }; + +template<> +struct Traits : detail::DirectTraits { }; + +template<> +struct Traits : detail::DirectTraits { }; + +template<> +struct Traits : detail::DirectTraits { }; + +template<> +struct Traits : detail::DirectTraits { }; + +template +struct Traits> { + static constexpr Type type = Traits::type; + static constexpr bool is_array = true; + using Element = E; + + static auto toScalar(const E& v) -> Scalar { return Traits::toScalar(v); } + + static auto fromScalar(const Scalar& s) -> std::optional { return Traits::fromScalar(s); } +}; + +template +auto toValue(const T& v) -> Value { + if constexpr (Traits::is_array) { + std::vector out; + out.reserve(v.size()); + for (const auto& element : v) { + out.push_back(Traits::toScalar(element)); + } + return Value {std::move(out)}; + } else { + return Value {Traits::toScalar(v)}; + } +} + +template +auto fromValue(const Value& v) -> std::optional { + if constexpr (Traits::is_array) { + const auto* items = std::get_if>(&v); + if (items == nullptr) { + return std::nullopt; + } + T out; + out.reserve(items->size()); + for (const auto& item : *items) { + auto element = Traits::fromScalar(item); + if (!element) { + return std::nullopt; + } + out.push_back(std::move(*element)); + } + return out; + } else { + const auto* scalar = std::get_if(&v); + return scalar != nullptr ? Traits::fromScalar(*scalar) : std::nullopt; + } +} + +} diff --git a/engine/src/toast/physics/debug_visuals.cpp b/engine/src/toast/physics/debug_visuals.cpp new file mode 100644 index 000000000..7de08d0a0 --- /dev/null +++ b/engine/src/toast/physics/debug_visuals.cpp @@ -0,0 +1,122 @@ +#include "debug_visuals.hpp" + +#include "physics_settings.hpp" +#include "simulator.hpp" + +#include +#include +#include +#include +#include + +namespace physics { +namespace { + +const glm::vec4 k_fixed {0.55F, 0.57F, 0.62F, 0.9F}; +const glm::vec4 k_kinematic {1.0F, 0.85F, 0.2F, 0.95F}; +const glm::vec4 k_awake {0.2F, 1.0F, 0.4F, 0.95F}; +const glm::vec4 k_asleep {0.3F, 0.55F, 1.0F, 0.95F}; +const glm::vec4 k_contact {1.0F, 0.3F, 0.3F, 1.0F}; +const glm::vec4 k_bounds {0.9F, 0.9F, 0.9F, 0.35F}; +const glm::vec4 k_velocity {0.3F, 0.9F, 1.0F, 1.0F}; +const glm::vec4 k_center {1.0F, 0.6F, 0.1F, 1.0F}; + +} + +auto debugColor(const Body& body) -> glm::vec4 { + glm::vec4 color = k_fixed; + switch (body.type) { + case BodyType::static_body: color = k_fixed; break; + case BodyType::kinematic_body: color = k_kinematic; break; + case BodyType::dynamic_body: color = body.awake ? k_awake : k_asleep; break; + } + if (!body.enabled) { + color.a *= 0.3F; + } + return color; +} + +void Simulator::drawDebugVisuals() const { + const PhysicsParams& params = tunables(); + const bool wanted = + params.draw_shapes || params.draw_bounds || params.draw_contacts || params.draw_velocity || params.draw_centers; + if (!wanted || renderer::VulkanRenderer::instance == nullptr) { + return; + } + ZoneScopedN("physics::DrawDebug"); + + if (!renderer::VulkanRenderer::instance->debugDrawEnabled()) { + renderer::VulkanRenderer::instance->setDebugDrawEnabled(true); + } + + const auto body_of = [this](const Shape& shape) -> const Body* { + if (shape.owner.slot >= m_bodies.size() || !m_bodies[shape.owner.slot].occupied) { + return nullptr; + } + return &m_bodies[shape.owner.slot].body; + }; + + for (const ShapeSlot& slot : m_shapes) { + if (!slot.occupied || !slot.shape.enabled) { + continue; + } + const Shape& shape = slot.shape; + const Body* body = body_of(shape); + if (body == nullptr) { + continue; + } + const glm::vec4 color = debugColor(*body); + + if (params.draw_bounds) { + const AABB bounds = worldShapeBounds(*body, shape); + debug::drawBox(bounds.min, bounds.max, k_bounds); + } + + if (params.draw_shapes) { + const glm::vec3 center = body->position + (body->rotation * shape.getLocalCenter()); + const glm::quat rotation = glm::normalize(body->rotation * shape.getLocalRotation()); + const glm::mat4 placed = glm::translate(glm::mat4(1.0F), center) * glm::mat4_cast(rotation); + switch (shape.type) { + case ShapeType::sphere: debug::drawSphere(center, shape.sphere.radius, color, 16); break; + case ShapeType::box: debug::drawShapeBox(glm::scale(placed, shape.box.size), color, false); break; + case ShapeType::capsule: debug::drawCapsule(placed, shape.capsule.radius, shape.capsule.height, color, false); break; + case ShapeType::voxel: { + const glm::vec3 middle = 0.5F * (shape.voxel.local_bounds.min + shape.voxel.local_bounds.max); + const glm::vec3 half = 0.5F * (shape.voxel.local_bounds.max - shape.voxel.local_bounds.min); + debug::drawOrientedBox(glm::translate(placed, middle), half, color); + break; + } + } + } + } + + if (params.draw_centers || params.draw_velocity) { + const float scale = params.velocity_scale; + for (const BodySlot& slot : m_bodies) { + if (!slot.occupied || !slot.body.enabled || slot.body.type == BodyType::static_body) { + continue; + } + const Body& body = slot.body; + const glm::vec3 center = body.worldCenterOfMass(); + if (params.draw_centers) { + debug::drawSphere(center, 0.04F, k_center, 8); + } + if (params.draw_velocity && body.awake && glm::dot(body.linear_velocity, body.linear_velocity) > 1.0e-6F) { + debug::drawArrow(center, center + (body.linear_velocity * scale), k_velocity, 0.08F); + } + } + } + + if (params.draw_contacts) { + const float length = params.contact_normal_length; + for (const Manifold& manifold : m_manifolds) { + for (size_t i = 0; i < manifold.contact_count && i < manifold.contacts.size(); ++i) { + const glm::vec3 point = manifold.contacts[i].position; + debug::drawSphere(point, 0.03F, k_contact, 8); + debug::drawLine(point, point + (manifold.normal * length), k_contact); + } + } + } +} + +} diff --git a/engine/src/toast/physics/debug_visuals.hpp b/engine/src/toast/physics/debug_visuals.hpp new file mode 100644 index 000000000..96d64f3b4 --- /dev/null +++ b/engine/src/toast/physics/debug_visuals.hpp @@ -0,0 +1,19 @@ +/** + * @file debug_visuals.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief How the simulation is drawn for the debug parameters + */ + +#pragma once +#include +#include +#include + +namespace physics { + +[[nodiscard]] +TOAST_API auto debugColor(const Body& body) -> glm::vec4; + +} diff --git a/engine/src/toast/physics/layers.cpp b/engine/src/toast/physics/layers.cpp index 106f83632..fcce5377d 100644 --- a/engine/src/toast/physics/layers.cpp +++ b/engine/src/toast/physics/layers.cpp @@ -1,6 +1,6 @@ #include "layers.hpp" -#include +#include "physics_settings.hpp" namespace physics { @@ -34,10 +34,24 @@ auto defaultLayer(int layer) -> LayerInfo { } } -auto settingKey(int layer, std::string_view field) -> std::string { - return "physics.layers." + std::to_string(layer) + "." + std::string {field}; } +auto defaultLayerNames() -> std::vector { + std::vector names; + names.reserve(k_layer_count); + for (int layer = 0; layer < k_layer_count; ++layer) { + names.push_back(defaultLayer(layer).name); + } + return names; +} + +auto defaultLayerAbbreviations() -> std::vector { + std::vector abbreviations; + abbreviations.reserve(k_layer_count); + for (int layer = 0; layer < k_layer_count; ++layer) { + abbreviations.push_back(defaultLayer(layer).abbreviation); + } + return abbreviations; } auto layerMask(const std::vector& layers) -> uint32_t { @@ -80,33 +94,33 @@ auto layerAbbreviation(int layer) -> std::string { return all.layers[layer].abbreviation; } -void registerLayerSettings() { - LayerTable& all = table(); +void registerLayerSettings(PhysicsParams& params) { { + LayerTable& all = table(); std::scoped_lock lock(all.mutex); for (int layer = 0; layer < k_layer_count; ++layer) { all.layers[layer] = defaultLayer(layer); } } - // Default can not be renamed so it has no setting - for (int layer = 1; layer < k_layer_count; ++layer) { - const LayerInfo info = defaultLayer(layer); - toast::settings::declareString(settingKey(layer, "name"), info.name, {.label = info.name, .category = "Tags", .hidden = true}) - .onChange([layer](const std::string& value) { - LayerTable& all = table(); - std::scoped_lock lock(all.mutex); - all.layers[layer].name = value; - }); - toast::settings::declareString( - settingKey(layer, "abbr"), info.abbreviation, {.label = info.abbreviation, .category = "Tags", .hidden = true} - ) - .onChange([layer](const std::string& value) { - LayerTable& all = table(); - std::scoped_lock lock(all.mutex); - all.layers[layer].abbreviation = value.substr(0, k_layer_abbreviation_length); - }); - } + toast::params::onChange(params.layer_names, [](const std::vector& names) { + LayerTable& all = table(); + std::scoped_lock lock(all.mutex); + for (int layer = 1; layer < k_layer_count; ++layer) { + const auto index = static_cast(layer); + all.layers[layer].name = index < names.size() && !names[index].empty() ? names[index] : defaultLayer(layer).name; + } + }); + toast::params::onChange(params.layer_abbreviations, [](const std::vector& abbreviations) { + LayerTable& all = table(); + std::scoped_lock lock(all.mutex); + for (int layer = 1; layer < k_layer_count; ++layer) { + const auto index = static_cast(layer); + all.layers[layer].abbreviation = index < abbreviations.size() && !abbreviations[index].empty() + ? abbreviations[index].substr(0, k_layer_abbreviation_length) + : defaultLayer(layer).abbreviation; + } + }); } } diff --git a/engine/src/toast/physics/layers.hpp b/engine/src/toast/physics/layers.hpp index 84acb630f..8ce631320 100644 --- a/engine/src/toast/physics/layers.hpp +++ b/engine/src/toast/physics/layers.hpp @@ -14,6 +14,8 @@ namespace physics { +struct PhysicsParams; + inline constexpr int k_layer_count = 32; inline constexpr uint32_t k_all_layers = 0xFFFF'FFFFu; inline constexpr size_t k_layer_abbreviation_length = 3; @@ -76,6 +78,6 @@ TOAST_API auto layerName(int layer) -> std::string; [[nodiscard]] TOAST_API auto layerAbbreviation(int layer) -> std::string; -void registerLayerSettings(); +void registerLayerSettings(PhysicsParams& params); } diff --git a/engine/src/toast/physics/physics_settings.cpp b/engine/src/toast/physics/physics_settings.cpp index e84391f18..b947e3357 100644 --- a/engine/src/toast/physics/physics_settings.cpp +++ b/engine/src/toast/physics/physics_settings.cpp @@ -2,689 +2,23 @@ #include "layers.hpp" -#include - namespace physics { -namespace { -using toast::settings::Meta; +namespace { -Tunables g_tunables; +auto instance() -> Tunables& { + static Tunables params; + return params; +} } auto tunables() -> const Tunables& { - return g_tunables; + return instance(); } void registerPhysicsSettings() { - registerLayerSettings(); - - const auto flt = [](std::string_view key, double value, Meta meta, float Tunables::* field) { - toast::settings::declareFloat(key, value, std::move(meta)).onChange([field](double v) { - g_tunables.*field = static_cast(v); - }); - }; - const auto uint_setting = [](std::string_view key, int64_t value, Meta meta, uint32_t Tunables::* field) { - toast::settings::declareInt(key, value, std::move(meta)).onChange([field](int64_t v) { - g_tunables.*field = static_cast(std::max(v, 0)); - }); - }; - - const auto gravity_axis = [](std::string_view key, std::string_view label, double value, int axis) { - toast::settings::declareFloat( - key, - value, - {.label = std::string {label}, - .category = "World", - .description = "Acceleration applied to every dynamic body, scaled per body by its gravity scale.", - .min = -100.0, - .max = 100.0, - .step = 0.1} - ) - .onChange([axis](double v) { g_tunables.gravity[axis] = static_cast(v); }); - }; - gravity_axis("physics.world.gravity_x", "Gravity X", 0.0, 0); - gravity_axis("physics.world.gravity_y", "Gravity Y", 0.0, 1); - gravity_axis("physics.world.gravity_z", "Gravity Z", -9.8, 2); - - flt("physics.world.air_density", - 1.225f, - {.label = "Air density", .category = "World", .min = 0.0f, .step = 0.1f}, - &Tunables::air_density); - - const auto wind_axis = [](std::string_view key, std::string_view label, double value, int axis) { - toast::settings::declareFloat( - key, value, {.label = std::string {label}, .category = "World", .min = -1000.0, .max = 1000.0, .step = 0.1} - ) - .onChange([axis](double v) { g_tunables.wind[axis] = static_cast(v); }); - }; - wind_axis("physics.world.wind_x", "Wind X", 0.0f, 0); - wind_axis("physics.world.wind_y", "Wind Y", 0.0f, 1); - wind_axis("physics.world.wind_z", "Wind Z", 0.0f, 2); - - flt("physics.world.wind_shelter_distance", - 64.0f, - {.label = "Wind shelter distance", - .category = "World", - .description = "A body with solid geometry this far upwind of it, like the wall of a building, feels no wind. 0 disables.", - .min = 0.0f, - .step = 1.0f}, - &Tunables::wind_shelter_distance); - - flt("physics.world.kill_plane_z", - -50.0f, - {.label = "Kill plane Z", - .category = "World", - .description = "Rigidbodies that fall below this height are destroyed", - .min = -100000.0f, - .max = 100000.0f, - .step = 1.0f}, - &Tunables::kill_plane_z); - - uint_setting( - "physics.solver.iterations", - 8, - {.label = "Iterations", - .category = "Solver", - .description = "Sequential impulse passes per step", - .min = 1.0, - .max = 32.0, - .step = 1.0}, - &Tunables::solver_iterations - ); - uint_setting( - "physics.solver.position_iterations", - 3, - {.label = "Position iterations", - .category = "Solver", - .description = "Passes that push overlapping bodies apart after the velocity solve", - .min = 1.0, - .max = 16.0, - .step = 1.0}, - &Tunables::position_iterations - ); - uint_setting( - "physics.solver.joint_substeps", - 4, - {.label = "Joint substeps", - .category = "Solver", - .description = "Times a step is split for bodies held by joints so swinging keeps its speed", - .min = 1.0, - .max = 16.0, - .step = 1.0}, - &Tunables::joint_substeps - ); - flt("physics.solver.penetration_slop", - 0.005, - {.label = "Penetration slop", - .category = "Solver", - .description = "Overlap left uncorrected, in metres", - .min = 0.0, - .max = 0.1, - .step = 0.001}, - &Tunables::penetration_slop); - flt("physics.solver.correction_beta", - 0.2, - {.label = "Correction beta", - .category = "Solver", - .description = "The fraction of the remaining overlap resolved each step", - .min = 0.0, - .max = 1.0, - .step = 0.01}, - &Tunables::correction_beta); - flt("physics.solver.max_correction", - 0.05, - {.label = "Max correction", - .category = "Solver", - .description = "Ceiling on one step's positional correction", - .min = 0.0, - .max = 1.0, - .step = 0.005}, - &Tunables::max_correction); - flt("physics.solver.bounce_threshold", - 1.0, - {.label = "Bounce threshold", - .category = "Solver", - .description = "Approach speed in m/s below which restitution is ignored", - .min = 0.0, - .max = 10.0, - .step = 0.1}, - &Tunables::bounce_threshold); - - flt("physics.sleep.linear_threshold", - 0.05, - {.label = "Linear threshold", - .category = "Sleep", - .description = "Speed in m/s a body must stay under to be eligible for sleep", - .min = 0.0, - .max = 1.0, - .step = 0.005}, - &Tunables::sleep_linear_threshold); - flt("physics.sleep.angular_threshold", - 0.05, - {.label = "Angular threshold", - .category = "Sleep", - .description = "Angular speed in rad/s a body must stay under to be eligible for sleep", - .min = 0.0, - .max = 1.0, - .step = 0.005}, - &Tunables::sleep_angular_threshold); - flt("physics.sleep.delay", - 0.5, - {.label = "Delay", - .category = "Sleep", - .description = "Seconds a body must stay under both thresholds before it sleeps", - .min = 0.0, - .max = 10.0, - .step = 0.1}, - &Tunables::sleep_delay); - flt("physics.sleep.drift", - 0.05, - {.label = "Drift", - .category = "Sleep", - .description = "Meters the farthest point of a body may travel during the delay and still sleep", - .min = 0.005, - .max = 0.5, - .step = 0.005}, - &Tunables::sleep_drift); - - toast::settings::declareFloat( - "physics.step.frequency", - 60.0, - {.label = "Frequency", .category = "Step", .description = "Fixed steps per second", .min = 15.0, .max = 240.0, .step = 1.0} - ) - .onChange([](double v) { g_tunables.frequency = v > 0.0 ? v : 60.0; }); - uint_setting( - "physics.step.max_substeps", - 8, - {.label = "Max substeps", - .category = "Step", - .description = "Ceiling on catch-up steps in a single frame", - .min = 1.0, - .max = 32.0, - .step = 1.0}, - &Tunables::max_substeps - ); - toast::settings::declareFloat( - "physics.step.max_burst_seconds", - 0.1, - {.label = "Max burst seconds", - .category = "Step", - .description = "Real-time budget for a fixed-step catch-up burst after its first step", - .min = 0.0, - .max = 1.0, - .step = 0.01} - ) - .onChange([](double v) { g_tunables.max_burst_seconds = std::max(v, 0.0); }); - - flt("physics.broadphase.fat_margin", - 0.1, - {.label = "Fat margin", - .category = "Broadphase", - .description = "Slack in metres added to a shape's bounds in the tree", - .min = 0.0, - .max = 1.0, - .step = 0.01}, - &Tunables::broadphase_fat_margin); - - flt("physics.broadphase.velocity_multiplier", - 2.0, - {.label = "Velocity multiplier", .category = "Broadphase", .min = 0.0, .max = 8.0, .step = 0.25}, - &Tunables::broadphase_velocity_multiplier); - - flt("physics.broadphase.rebuild_fraction", - 0.25, - {.label = "Rebuild fraction", .category = "Broadphase", .min = 0.0, .max = 2.0, .step = 0.05}, - &Tunables::broadphase_rebuild_fraction); - - uint_setting( - "physics.fracture.max_connectivity_jobs_per_tick", - 24, - {.label = "Max connectivity jobs per tick", - .category = "Fracture", - .description = "Concurrent connectivity analyses started in one physics tick", - .min = 1.0, - .max = 256.0, - .step = 1.0}, - &Tunables::max_connectivity_jobs_per_tick - ); - uint_setting( - "physics.fracture.max_spawns_per_step", - 8, - {.label = "Max fragment spawns per step", - .category = "Fracture", - .description = "Fragments promoted to their own bodies in one step", - .min = 0.0, - .max = 64.0, - .step = 1.0}, - &Tunables::max_fragment_spawns_per_step - ); - uint_setting( - "physics.fracture.max_active_fragments", - 96, - {.label = "Max active fragments", - .category = "Fracture", - .description = "Awake fragment budget before nearly settled debris is forced to sleep", - .min = 0.0, - .max = 16384.0, - .step = 64.0}, - &Tunables::max_active_fragments - ); - uint_setting( - "physics.fracture.pool_headroom", - 4096, - {.label = "Fragment pool headroom", - .category = "Fracture", - .description = "Bricks kept spare for fragments", - .min = 0.0, - .max = 65536.0, - .step = 256.0}, - &Tunables::fragment_pool_headroom - ); - uint_setting( - "physics.fracture.min_fragment_voxels", - 4, - {.label = "Min fragment voxels", - .category = "Fracture", - .description = "Disconnected pieces smaller than this are discarded instead of becoming debris", - .min = 1.0, - .max = 256.0, - .step = 1.0}, - &Tunables::min_fragment_voxels - ); - uint_setting( - "physics.fracture.despawn_max_voxels", - 16, - {.label = "Despawn max voxels", - .category = "Fracture", - .description = "Largest settled fragment eligible for automatic despawning", - .min = 0.0, - .max = 1024.0, - .step = 1.0}, - &Tunables::fragment_despawn_max_voxels - ); - uint_setting( - "physics.fracture.large_debris_min_voxels", - 16, - {.label = "Large debris min voxels", - .category = "Fracture", - .description = "Fragments with at least this many voxels go on the Large debris layer instead of Small debris", - .min = 1.0, - .max = 4096.0, - .step = 1.0}, - &Tunables::large_debris_min_voxels - ); - flt("physics.fracture.despawn_settle_seconds", - 3.0, - {.label = "Despawn settle time", - .category = "Fracture", - .description = "Seconds a small fragment must remain asleep before despawning", - .min = 0.0, - .max = 60.0, - .step = 0.25}, - &Tunables::fragment_despawn_settle_seconds); - flt("physics.fracture.force_sleep_slack", - 4.0, - {.label = "Force sleep slack", - .category = "Fracture", - .description = "Multiplier on sleep velocity thresholds when enforcing the active fragment budget", - .min = 1.0, - .max = 64.0, - .step = 0.5}, - &Tunables::force_sleep_slack); - flt("physics.fracture.sleep_scale", - 3.0, - {.label = "Fragment sleep scale", - .category = "Fracture", - .description = "Multiplier on the sleep thresholds for fragments so debris settles sooner than other bodies", - .min = 1.0, - .max = 20.0, - .step = 0.5}, - &Tunables::fragment_sleep_scale); - toast::settings::declareInt( - "physics.fracture.max_fragment_extent_bricks", - 1, - {.label = "Max fragment extent (bricks)", - .category = "Fracture", - .description = "Largest piece, in bricks along any axis, still treated as a fragment", - .min = 1.0, - .max = 16.0, - .step = 1.0} - ) - .onChange([](int64_t v) { g_tunables.max_fragment_extent_bricks = static_cast(std::max(v, 1)); }); - flt("physics.fracture.shell_voxels", - 1.0, - {.label = "Fracture shell voxels", - .category = "Fracture", - .description = "Thickness in voxels of the shell a fracture carves around an impact", - .min = 0.0, - .max = 16.0, - .step = 0.5}, - &Tunables::fracture_shell_voxels); - flt("physics.fracture.depth_share", - 0.5, - {.label = "Depth share", - .category = "Fracture", - .description = "Energy left after the fracture pokes through", - .min = 0.0, - .max = 1.0, - .step = 0.05}, - &Tunables::fracture_depth_share); - flt("physics.fracture.max_depth", - 2.0, - {.label = "Max depth", - .category = "Fracture", - .description = "Meters a single hit can dig past its fracture radius", - .min = 0.0, - .max = 16.0, - .step = 0.1}, - &Tunables::fracture_max_depth); - flt("physics.fracture.max_overshoot", - 2.0, - {.label = "Max overshoot", - .category = "Fracture", - .description = "Most a hit can widen past its fracture radius", - .min = 0.0, - .max = 16.0, - .step = 0.1}, - &Tunables::fracture_max_overshoot); - flt("physics.fracture.explosion_max_radius", - 8.0, - {.label = "Explosion max radius", - .category = "Fracture", - .description = "Meters an explosion can break or push things at, unless it sets its own radius", - .min = 0.0, - .max = 64.0, - .step = 0.5}, - &Tunables::explosion_max_radius); - flt("physics.fracture.explosion_falloff", - 2.0, - {.label = "Explosion falloff", - .category = "Fracture", - .description = "2 is the inverse square", - .min = 0.5, - .max = 8.0, - .step = 0.25}, - &Tunables::explosion_falloff); - flt("physics.fracture.explosion_chunk_size", - 1.0, - {.label = "Explosion chunk size", - .category = "Fracture", - .description = "Meters across the chunks an explosion breaks material into", - .min = 0.2, - .max = 4.0, - .step = 0.1}, - &Tunables::explosion_chunk_size); - flt("physics.fracture.explosion_debris_ratio", - 8.0, - {.label = "Explosion debris ratio", - .category = "Fracture", - .description = "Material hit by a blast this many times its toughness turns to debris instead of chunks", - .min = 1.0, - .max = 64.0, - .step = 0.5}, - &Tunables::explosion_debris_ratio); - flt("physics.fracture.explosion_shatter_width", - 0.6, - {.label = "Explosion shatter width", - .category = "Fracture", - .description = "Meters of cracked material around the hole an explosion leaves, 0 for none", - .min = 0.0, - .max = 4.0, - .step = 0.1}, - &Tunables::explosion_shatter_width); - flt("physics.fracture.explosion_max_speed", - 20.0, - {.label = "Explosion max speed", - .category = "Fracture", - .description = "Fastest an explosion throws a chunk, debris or body, in m/s. Faster tunnels through thin colliders", - .min = 1.0, - .max = 100.0, - .step = 1.0}, - &Tunables::explosion_max_speed); - uint_setting( - "physics.fracture.explosion_max_fragments", - 48, - {.label = "Explosion max fragments", - .category = "Fracture", - .description = "Chunks one explosion can promote to their own bodies per shape; the rest become debris", - .min = 0.0, - .max = 256.0, - .step = 1.0}, - &Tunables::explosion_max_fragments - ); - uint_setting( - "physics.fracture.impact_max_hardness", - 1, - {.label = "Impact max hardness", - .category = "Fracture", - .description = "Hardest material collisions between bodies can break", - .min = 0.0, - .max = 2.0, - .step = 1.0}, - &Tunables::impact_max_hardness - ); - flt("physics.fracture.bond_cost", - 1.0, - {.label = "Bond cost", .category = "Fracture", .min = 0.0, .max = 16.0, .step = 0.1}, - &Tunables::fracture_bond_cost); - uint_setting( - "physics.fracture.max_unglue_voxels", - 4096, - {.label = "Max unglue voxels", .category = "Fracture", .min = 0.0, .max = 1000000.0, .step = 64.0}, - &Tunables::fracture_max_unglue_voxels - ); - uint_setting( - "physics.fracture.max_shatter_cells", - 128, - {.label = "Max shatter cells", .category = "Shatter", .min = 2.0, .max = 1024.0, .step = 8.0}, - &Tunables::fracture_max_shatter_cells - ); - flt("physics.fracture.max_shatter_distance", - 8.0, - {.label = "Max shatter distance", .category = "Shatter", .min = 0.1f, .max = 64.0f, .step = 0.5f}, - &Tunables::fracture_max_shatter_distance); - uint_setting( - "physics.debris.max_spawns_per_step", - 512, - {.label = "Max spawns per step", .category = "Debris", .min = 0.0, .max = 16384.0, .step = 16.0}, - &Tunables::debris_max_spawns_per_step - ); - flt("physics.debris.speed_scale", - 1.0, - {.label = "Speed scale", .category = "Debris", .min = 0.0f, .max = 8.0f, .step = 0.1f}, - &Tunables::debris_speed_scale); - flt("physics.debris.density_multiplier", - 1.0, - {.label = "Density multiplier", - .category = "Debris", - .description = "Heavier debris is thrown slower by the same blast", - .min = 0.1f, - .max = 100.0f, - .step = 0.1f}, - &Tunables::debris_density_multiplier); - flt("physics.debris.max_speed", - 12.0, - {.label = "Max speed", - .category = "Debris", - .description = "Fastest a piece of debris can be thrown, in m/s", - .min = 0.5f, - .max = 40.0f, - .step = 0.5f}, - &Tunables::debris_max_speed); - flt("physics.debris.max_spin", - 20.0, - {.label = "Max spin", - .category = "Debris", - .description = "Fastest a piece of debris can spin, in rad/s", - .min = 1.0f, - .max = 60.0f, - .step = 1.0f}, - &Tunables::debris_max_spin); - flt("physics.debris.lifetime", - 12.0, - {.label = "Lifetime", .category = "Debris", .min = 0.5, .max = 600.0, .step = 0.5}, - &Tunables::debris_lifetime); - flt("physics.debris.lifetime_jitter", - 0.3, - {.label = "Lifetime jitter", - .category = "Debris", - .description = "Each piece lives lifetime times one plus or minus this so a burst does not vanish at once", - .min = 0.0, - .max = 0.9, - .step = 0.05}, - &Tunables::debris_lifetime_jitter); - uint_setting( - "physics.debris.max_particles", - 16384, - {.label = "Max particles", - .category = "Debris", - .description = "Past this the oldest pieces shrink away to make room for new ones", - .min = 256.0, - .max = 262144.0, - .step = 1024.0, - .requires_restart = true}, - &Tunables::debris_max_particles - ); - flt("physics.debris.restitution", - 0.3, - {.label = "Restitution", .category = "Debris", .min = 0.0, .max = 1.0, .step = 0.05}, - &Tunables::debris_restitution); - flt("physics.debris.friction", - 0.6, - {.label = "Friction", .category = "Debris", .min = 0.0, .max = 1.0, .step = 0.05}, - &Tunables::debris_friction); - - uint_setting( - "physics.jobs.min_bounds_per_job", - 32, - {.label = "Min bounds per job", - .category = "Jobs", - .description = "Broadphase bounds updates below this run inline - a job costs more than the work", - .min = 1.0, - .max = 1024.0, - .step = 1.0}, - &Tunables::min_bounds_per_job - ); - uint_setting( - "physics.jobs.min_candidates_per_job", - 2, - {.label = "Min candidates per job", - .category = "Jobs", - .description = "Narrow phase candidate pairs below this run inline", - .min = 1.0, - .max = 1024.0, - .step = 1.0}, - &Tunables::min_candidates_per_job - ); - uint_setting( - "physics.jobs.min_manifolds_per_job", - 4, - {.label = "Min manifolds per job", - .category = "Jobs", - .description = "Active manifolds below this run constraint preparation inline", - .min = 1.0, - .max = 1024.0, - .step = 1.0}, - &Tunables::min_manifolds_per_job - ); - uint_setting( - "physics.jobs.min_shapes_per_query_job", - 16, - {.label = "Min shapes per query job", - .category = "Jobs", - .description = "Leaf shapes below this run broadphase tree queries inline", - .min = 1.0, - .max = 1024.0, - .step = 1.0}, - &Tunables::min_shapes_per_query_job - ); - uint_setting( - "physics.jobs.min_bodies_per_job", - 64, - {.label = "Min bodies per job", - .category = "Jobs", - .description = "Bodies below this run integration inline instead of across the thread pool", - .min = 1.0, - .max = 4096.0, - .step = 1.0}, - &Tunables::min_bodies_per_job - ); - uint_setting( - "physics.jobs.min_wave_constraints_for_dispatch", - 512, - {.label = "Min wave constraints per dispatch", - .category = "Jobs", - .description = "Constraint waves below this size solve inline", - .min = 1.0, - .max = 65536.0, - .step = 1.0}, - &Tunables::min_wave_constraints_for_dispatch - ); - uint_setting( - "physics.jobs.min_wave_joints_for_dispatch", - 64, - {.label = "Min wave joints per dispatch", - .category = "Jobs", - .description = "Joint waves below this size solve inline", - .min = 1.0, - .max = 65536.0, - .step = 1.0}, - &Tunables::min_wave_joints_for_dispatch - ); - uint_setting( - "physics.jobs.box_voxel_split_min_voxels", - 500000, - {.label = "Box-voxel split threshold", - .category = "Jobs", - .description = "Box-voxel pairs above this surface area split across jobs, kept high until measured", - .min = 1.0, - .max = 1000000.0, - .step = 1.0}, - &Tunables::box_voxel_split_min_voxels - ); - uint_setting( - "physics.jobs.voxel_voxel_split_min_voxels", - 250000, - {.label = "Voxel-voxel split threshold", - .category = "Jobs", - .description = "Same reasoning and same deliberately-off-for-now state as box_voxel_split_min_voxels", - .min = 1.0, - .max = 1000000.0, - .step = 1.0}, - &Tunables::voxel_voxel_split_min_voxels - ); - uint_setting( - "physics.jobs.voxel_pair_split_regions", - 8, - {.label = "Voxel pair split regions", - .category = "Jobs", - .description = "How many jobs a split box-voxel or voxel-voxel pair divides into", - .min = 1.0, - .max = 64.0, - .step = 1.0}, - &Tunables::voxel_pair_split_regions - ); - toast::settings::declareBool( - "physics.debug.time_narrow_pairs", - false, - {.label = "Time narrow phase pairs", - .category = "Debug", - .description = "Times every narrow phase pair per shape type for the debug overlay"} - ) - .onChange([](bool v) { g_tunables.time_narrow_pairs = v; }); - uint_setting( - "physics.character.sweep_refine_iterations", - 6, - {.label = "Sweep refine iterations", - .category = "Character", - .description = "Bisection steps a sweep refines by once it hits something, a clear sweep never pays it", - .min = 1.0, - .max = 32.0, - .step = 1.0}, - &Tunables::sweep_refine_iterations - ); + registerLayerSettings(instance()); } } diff --git a/engine/src/toast/physics/physics_settings.hpp b/engine/src/toast/physics/physics_settings.hpp index 303b4ae96..07165b8c4 100644 --- a/engine/src/toast/physics/physics_settings.hpp +++ b/engine/src/toast/physics/physics_settings.hpp @@ -7,82 +7,518 @@ #pragma once #include #include +#include #include +#include +#include namespace physics { -struct Tunables { - glm::vec3 gravity {0.0f, 0.0f, -9.8f}; - uint32_t solver_iterations = 8; - float penetration_slop = 0.005f; - float correction_beta = 0.2f; - float max_correction = 0.05f; - float bounce_threshold = 1.0f; - float sleep_linear_threshold = 0.05f; - float sleep_angular_threshold = 0.05f; - float sleep_delay = 0.5f; - float sleep_drift = 0.05f; - double frequency = 60.0; - uint32_t max_substeps = 8; - double max_burst_seconds = 0.1; - float broadphase_fat_margin = 0.1f; - float broadphase_velocity_multiplier = 2.0f; - float broadphase_rebuild_fraction = 0.25f; - uint32_t max_connectivity_jobs_per_tick = 24; - uint32_t max_fragment_spawns_per_step = 8; - uint32_t max_active_fragments = 96; - uint32_t fragment_pool_headroom = 4096; - uint32_t min_fragment_voxels = 4; - uint32_t fragment_despawn_max_voxels = 16; - uint32_t large_debris_min_voxels = 16; - float fragment_despawn_settle_seconds = 3.0f; - float force_sleep_slack = 4.0f; - float fragment_sleep_scale = 3.0f; - int32_t max_fragment_extent_bricks = 1; - float fracture_shell_voxels = 1.0f; - float fracture_depth_share = 0.5f; - float fracture_max_depth = 2.0f; - float fracture_max_overshoot = 2.0f; - float fracture_bond_cost = 1.0f; - uint32_t fracture_max_unglue_voxels = 4096; - uint32_t fracture_max_shatter_cells = 128; - float fracture_max_shatter_distance = 8.0f; - uint32_t debris_max_spawns_per_step = 512; - float debris_speed_scale = 1.0f; - float debris_density_multiplier = 1.0f; - float debris_max_speed = 12.0f; - float debris_max_spin = 20.0f; - float debris_lifetime = 12.0f; - float debris_lifetime_jitter = 0.3f; - uint32_t debris_max_particles = 16384; - float debris_restitution = 0.3f; - float debris_friction = 0.6f; - float explosion_max_radius = 8.0f; - float explosion_falloff = 2.0f; - float explosion_chunk_size = 1.0f; - float explosion_debris_ratio = 8.0f; - float explosion_shatter_width = 0.6f; - uint32_t explosion_max_fragments = 48; - float explosion_max_speed = 20.0f; - uint32_t impact_max_hardness = 1; - uint32_t min_bounds_per_job = 32; - uint32_t min_candidates_per_job = 2; - uint32_t min_manifolds_per_job = 4; - uint32_t min_shapes_per_query_job = 16; - uint32_t min_bodies_per_job = 64; - uint32_t min_wave_constraints_for_dispatch = 512; - uint32_t min_wave_joints_for_dispatch = 64; - uint32_t box_voxel_split_min_voxels = 500000; - uint32_t voxel_voxel_split_min_voxels = 250000; - uint32_t voxel_pair_split_regions = 8; - uint32_t sweep_refine_iterations = 6; - uint32_t position_iterations = 3; - uint32_t joint_substeps = 4; - float air_density = 1.225f; - glm::vec3 wind = {0.0f, 0.0f, 0.0f}; - float wind_shelter_distance = 64.0f; - float kill_plane_z = -50.0f; - bool time_narrow_pairs = false; +[[nodiscard]] +TOAST_API auto defaultLayerNames() -> std::vector; + +[[nodiscard]] +TOAST_API auto defaultLayerAbbreviations() -> std::vector; + +struct PhysicsParams : toast::params::Group<"physics"> { + using Kind = toast::params::Kind; + + glm::vec3 gravity = param( + &gravity, "world.gravity", {0.0f, 0.0f, -9.8f}, + {.name = "Gravity", + .min = glm::vec3 {-100.0f}, + .max = glm::vec3 {100.0f}, + .unit = "m/s²", + .description = "Pull on every body"} + ); + float air_density = param( + &air_density, "world.air_density", 1.225f, + {.name = "Air density", .min = 0.0f, .unit = "kg/m³", .description = "kg/m³. More makes drag stronger"} + ); + glm::vec3 wind = param( + &wind, "world.wind", {0.0f, 0.0f, 0.0f}, + {.name = "Wind", .min = glm::vec3 {-1000.0f}, .max = glm::vec3 {1000.0f}, .unit = "m/s", .description = "Wind speed"} + ); + float wind_shelter_distance = param( + &wind_shelter_distance, "world.wind_shelter_distance", 64.0f, + {.name = "Wind shelter distance", + .min = 0.0f, + .unit = "m", + .description = "Solid geometry this far upwind blocks the wind. 0 turns it off"} + ); + float kill_plane_z = param( + &kill_plane_z, "world.kill_plane_z", -50.0f, + {.name = "Kill plane Z", + .min = -100000.0f, + .max = 100000.0f, + .unit = "m", + .description = "Bodies that fall below this height are destroyed"} + ); + uint32_t solver_iterations = param( + &solver_iterations, "solver.iterations", 8, + {.name = "Iterations", .min = 1, .max = 32, .description = "Passes per step. More is stiffer and slower"} + ); + uint32_t position_iterations = param( + &position_iterations, "solver.position_iterations", 3, + {.name = "Position iterations", + .min = 1, + .max = 16, + .kind = Kind::advanced, + .description = "Extra passes that push overlaps apart"} + ); + uint32_t joint_substeps = param( + &joint_substeps, "solver.joint_substeps", 4, + {.name = "Joint substeps", + .min = 1, + .max = 16, + .kind = Kind::advanced, + .description = "Splits each step for bodies on joints so swings keep their speed"} + ); + float penetration_slop = param( + &penetration_slop, "solver.penetration_slop", 0.005f, + {.name = "Penetration slop", .min = 0.0f, .max = 0.1f, .unit = "m", .description = "Overlap left alone"} + ); + float correction_beta = param( + &correction_beta, "solver.correction_beta", 0.2f, + {.name = "Correction beta", + .min = 0.0f, + .max = 1.0f, + .kind = Kind::advanced, + .description = "Share of an overlap fixed each step"} + ); + float max_correction = param( + &max_correction, "solver.max_correction", 0.05f, + {.name = "Max correction", .min = 0.0f, .max = 1.0f, .unit = "m", .description = "Most an overlap is pushed in one step"} + ); + float bounce_threshold = param( + &bounce_threshold, "solver.bounce_threshold", 1.0f, + {.name = "Bounce threshold", + .min = 0.0f, + .max = 10.0f, + .unit = "m/s", + .description = "Hits slower than this (m/s) do not bounce"} + ); + float sleep_linear_threshold = param( + &sleep_linear_threshold, "sleep.linear_threshold", 0.05f, + {.name = "Linear threshold", + .min = 0.0f, + .max = 1.0f, + .unit = "m/s", + .description = "Slower than this (m/s), a body can fall asleep"} + ); + float sleep_angular_threshold = param( + &sleep_angular_threshold, "sleep.angular_threshold", 0.05f, + {.name = "Angular threshold", + .min = 0.0f, + .max = 1.0f, + .unit = "rad/s", + .description = "Spinning slower than this (rad/s), a body can fall asleep"} + ); + float sleep_delay = param( + &sleep_delay, "sleep.delay", 0.5f, + {.name = "Delay", .min = 0.0f, .max = 10.0f, .unit = "s", .description = "Seconds a body stays still before it sleeps"} + ); + float sleep_drift = param( + &sleep_drift, "sleep.drift", 0.05f, + {.name = "Drift", .min = 0.005f, .max = 0.5f, .unit = "m", .description = "How far a body may wander in that time"} + ); + double frequency = param( + &frequency, "step.frequency", 60.0, + {.name = "Frequency", .min = 15.0, .max = 240.0, .unit = "Hz", .description = "Physics steps per second"} + ); + uint32_t max_substeps = param( + &max_substeps, "step.max_substeps", 8, + {.name = "Max substeps", .min = 1, .max = 32, .description = "Most steps one frame may catch up with"} + ); + double max_burst_seconds = param( + &max_burst_seconds, "step.max_burst_seconds", 0.1, + {.name = "Max burst seconds", + .min = 0.0, + .max = 1.0, + .unit = "s", + .kind = Kind::advanced, + .description = "Most real time a catch-up may take after its first step"} + ); + float broadphase_fat_margin = param( + &broadphase_fat_margin, "broadphase.fat_margin", 0.1f, + {.name = "Fat margin", + .min = 0.0f, + .max = 1.0f, + .unit = "m", + .kind = Kind::advanced, + .description = "Padding around each shape's bounds"} + ); + float broadphase_velocity_multiplier = param( + &broadphase_velocity_multiplier, "broadphase.velocity_multiplier", 2.0f, + {.name = "Velocity multiplier", + .min = 0.0f, + .max = 8.0f, + .kind = Kind::advanced, + .description = "How far bounds stretch ahead of a moving shape, in steps"} + ); + float broadphase_rebuild_fraction = param( + &broadphase_rebuild_fraction, "broadphase.rebuild_fraction", 0.25f, + {.name = "Rebuild fraction", + .min = 0.0f, + .max = 2.0f, + .kind = Kind::advanced, + .description = "Share of shapes that may move before the tree is rebuilt"} + ); + uint32_t max_connectivity_jobs_per_tick = param( + &max_connectivity_jobs_per_tick, "fracture.max_connectivity_jobs_per_tick", 24, + {.name = "Max connectivity jobs per tick", + .min = 1, + .max = 256, + .kind = Kind::advanced, + .description = "Pieces checked for being cut off, per tick"} + ); + uint32_t max_fragment_spawns_per_step = param( + &max_fragment_spawns_per_step, "fracture.max_spawns_per_step", 8, + {.name = "Max fragment spawns per step", .min = 0, .max = 64, .description = "Fragments that become bodies per step"} + ); + uint32_t max_active_fragments = param( + &max_active_fragments, "fracture.max_active_fragments", 96, + {.name = "Max active fragments", + .min = 0, + .max = 16384, + .description = "Awake fragments allowed before settled ones are put to sleep"} + ); + uint32_t fragment_pool_headroom = param( + &fragment_pool_headroom, "fracture.pool_headroom", 4096, + {.name = "Fragment pool headroom", + .min = 0, + .max = 65536, + .kind = Kind::advanced, + .description = "Spare bricks kept for fragments"} + ); + uint32_t min_fragment_voxels = param( + &min_fragment_voxels, "fracture.min_fragment_voxels", 4, + {.name = "Min fragment voxels", + .min = 1, + .max = 256, + .unit = "voxels", + .description = "Smaller pieces are discarded instead of becoming debris"} + ); + uint32_t fragment_despawn_max_voxels = param( + &fragment_despawn_max_voxels, "fracture.despawn_max_voxels", 16, + {.name = "Despawn max voxels", + .min = 0, + .max = 1024, + .unit = "voxels", + .description = "Largest fragment that may despawn on its own"} + ); + uint32_t large_debris_min_voxels = param( + &large_debris_min_voxels, "fracture.large_debris_min_voxels", 16, + {.name = "Large debris min voxels", + .min = 1, + .max = 4096, + .unit = "voxels", + .description = "From this many voxels a fragment goes on the large debris layer"} + ); + float fragment_despawn_settle_seconds = param( + &fragment_despawn_settle_seconds, "fracture.despawn_settle_seconds", 3.0f, + {.name = "Despawn settle time", + .min = 0.0f, + .max = 60.0f, + .unit = "s", + .description = "Seconds a small fragment sleeps before it despawns"} + ); + float force_sleep_slack = param( + &force_sleep_slack, "fracture.force_sleep_slack", 4.0f, + {.name = "Force sleep slack", + .min = 1.0f, + .max = 64.0f, + .kind = Kind::advanced, + .description = "Sleep limits are this much looser while over the fragment budget"} + ); + float fragment_sleep_scale = param( + &fragment_sleep_scale, "fracture.sleep_scale", 3.0f, + {.name = "Fragment sleep scale", + .min = 1.0f, + .max = 20.0f, + .description = "Fragments sleep with the limits scaled by this, so debris settles sooner"} + ); + int32_t max_fragment_extent_bricks = param( + &max_fragment_extent_bricks, "fracture.max_fragment_extent_bricks", 1, + {.name = "Max fragment extent (bricks)", + .min = 1, + .max = 16, + .unit = "bricks", + .kind = Kind::advanced, + .description = "Largest piece, in bricks along any axis, that still counts as a fragment"} + ); + float fracture_shell_voxels = param( + &fracture_shell_voxels, "fracture.shell_voxels", 1.0f, + {.name = "Fracture shell voxels", + .min = 0.0f, + .max = 16.0f, + .unit = "voxels", + .description = "Thickness of the shell carved around a hit"} + ); + float fracture_depth_share = param( + &fracture_depth_share, "fracture.depth_share", 0.5f, + {.name = "Depth share", .min = 0.0f, .max = 1.0f, .description = "Energy that carries on after a hit breaks through"} + ); + float fracture_max_depth = param( + &fracture_max_depth, "fracture.max_depth", 2.0f, + {.name = "Max depth", .min = 0.0f, .max = 16.0f, .unit = "m", .description = "Most a hit digs past its radius"} + ); + float fracture_max_overshoot = param( + &fracture_max_overshoot, "fracture.max_overshoot", 2.0f, + {.name = "Max overshoot", .min = 0.0f, .max = 16.0f, .description = "Most a hit widens past its radius"} + ); + float explosion_max_radius = param( + &explosion_max_radius, "fracture.explosion_max_radius", 8.0f, + {.name = "Explosion max radius", + .min = 0.0f, + .max = 64.0f, + .unit = "m", + .description = "Reach of an explosion that sets no radius of its own"} + ); + float explosion_falloff = param( + &explosion_falloff, "fracture.explosion_falloff", 2.0f, + {.name = "Explosion falloff", + .min = 0.5f, + .max = 8.0f, + .description = "How fast force fades with distance. 2 is inverse square"} + ); + float explosion_chunk_size = param( + &explosion_chunk_size, "fracture.explosion_chunk_size", 1.0f, + {.name = "Explosion chunk size", + .min = 0.2f, + .max = 4.0f, + .unit = "m", + .description = "Size of the chunks a blast breaks things into"} + ); + float explosion_debris_ratio = param( + &explosion_debris_ratio, "fracture.explosion_debris_ratio", 8.0f, + {.name = "Explosion debris ratio", + .min = 1.0f, + .max = 64.0f, + .description = "A blast this many times tougher than the material turns it to debris"} + ); + float explosion_shatter_width = param( + &explosion_shatter_width, "fracture.explosion_shatter_width", 0.6f, + {.name = "Explosion shatter width", + .min = 0.0f, + .max = 4.0f, + .unit = "m", + .description = "Cracked material left around the hole. 0 for none"} + ); + float explosion_max_speed = param( + &explosion_max_speed, "fracture.explosion_max_speed", 20.0f, + {.name = "Explosion max speed", + .min = 1.0f, + .max = 100.0f, + .unit = "m/s", + .description = "Fastest a blast throws anything. Too fast tunnels through thin colliders"} + ); + uint32_t explosion_max_fragments = param( + &explosion_max_fragments, "fracture.explosion_max_fragments", 48, + {.name = "Explosion max fragments", + .min = 0, + .max = 256, + .description = "Chunks per shape that become bodies. The rest turn to debris"} + ); + uint32_t impact_max_hardness = param( + &impact_max_hardness, "fracture.impact_max_hardness", 1, + {.name = "Impact max hardness", .min = 0, .max = 2, .description = "Hardest material a collision can break"} + ); + float fracture_bond_cost = param( + &fracture_bond_cost, "fracture.bond_cost", 1.0f, {.name = "Bond cost", .min = 0.0f, .max = 16.0f, .kind = Kind::advanced} + ); + uint32_t fracture_max_unglue_voxels = param( + &fracture_max_unglue_voxels, "fracture.max_unglue_voxels", 4096, + {.name = "Max unglue voxels", .min = 0, .max = 1000000, .kind = Kind::advanced} + ); + uint32_t fracture_max_shatter_cells = param( + &fracture_max_shatter_cells, "fracture.max_shatter_cells", 128, + {.name = "Max shatter cells", .min = 2, .max = 1024, .kind = Kind::advanced} + ); + float fracture_max_shatter_distance = param( + &fracture_max_shatter_distance, "fracture.max_shatter_distance", 8.0f, + {.name = "Max shatter distance", .min = 0.1f, .max = 64.0f, .kind = Kind::advanced} + ); + uint32_t debris_max_spawns_per_step = param( + &debris_max_spawns_per_step, "debris.max_spawns_per_step", 512, + {.name = "Max spawns per step", .min = 0, .max = 16384, .description = "Debris pieces created per step"} + ); + float debris_speed_scale = param( + &debris_speed_scale, "debris.speed_scale", 1.0f, + {.name = "Speed scale", .min = 0.0f, .max = 8.0f, .description = "Scales how fast debris is thrown"} + ); + float debris_density_multiplier = param( + &debris_density_multiplier, "debris.density_multiplier", 1.0f, + {.name = "Density multiplier", .min = 0.1f, .max = 100.0f, .description = "Heavier debris is thrown slower"} + ); + float debris_max_speed = param( + &debris_max_speed, "debris.max_speed", 12.0f, + {.name = "Max speed", .min = 0.5f, .max = 40.0f, .unit = "m/s", .description = "Fastest a piece is thrown"} + ); + float debris_max_spin = param( + &debris_max_spin, "debris.max_spin", 20.0f, + {.name = "Max spin", .min = 1.0f, .max = 60.0f, .unit = "rad/s", .description = "Fastest a piece spins, in rad/s"} + ); + float debris_lifetime = param( + &debris_lifetime, "debris.lifetime", 12.0f, + {.name = "Lifetime", .min = 0.5f, .max = 600.0f, .unit = "s", .description = "Seconds a piece lasts"} + ); + float debris_lifetime_jitter = param( + &debris_lifetime_jitter, "debris.lifetime_jitter", 0.3f, + {.name = "Lifetime jitter", + .min = 0.0f, + .max = 0.9f, + .description = "Random spread on the lifetime, so a burst does not vanish at once"} + ); + uint32_t debris_max_particles = param( + &debris_max_particles, "debris.max_particles", 16384, + {.name = "Max particles", + .min = 256, + .max = 262144, + .description = "Past this the oldest pieces shrink away", + .requires_restart = true} + ); + float debris_restitution = + param(&debris_restitution, "debris.restitution", 0.3f, {.name = "Restitution", .min = 0.0f, .max = 1.0f}); + float debris_friction = param(&debris_friction, "debris.friction", 0.6f, {.name = "Friction", .min = 0.0f, .max = 1.0f}); + uint32_t min_bounds_per_job = param( + &min_bounds_per_job, "jobs.min_bounds_per_job", 32, + {.name = "Min bounds per job", + .min = 1, + .max = 1024, + .kind = Kind::advanced, + .description = "Fewer bounds than this update on the calling thread"} + ); + uint32_t min_candidates_per_job = param( + &min_candidates_per_job, "jobs.min_candidates_per_job", 2, + {.name = "Min candidates per job", + .min = 1, + .max = 1024, + .kind = Kind::advanced, + .description = "Fewer candidate pairs than this are tested inline"} + ); + uint32_t min_manifolds_per_job = param( + &min_manifolds_per_job, "jobs.min_manifolds_per_job", 4, + {.name = "Min manifolds per job", + .min = 1, + .max = 1024, + .kind = Kind::advanced, + .description = "Fewer contacts than this are prepared inline"} + ); + uint32_t min_shapes_per_query_job = param( + &min_shapes_per_query_job, "jobs.min_shapes_per_query_job", 16, + {.name = "Min shapes per query job", + .min = 1, + .max = 1024, + .kind = Kind::advanced, + .description = "Fewer shapes than this are queried inline"} + ); + uint32_t min_bodies_per_job = param( + &min_bodies_per_job, "jobs.min_bodies_per_job", 64, + {.name = "Min bodies per job", + .min = 1, + .max = 4096, + .kind = Kind::advanced, + .description = "Fewer bodies than this integrate inline"} + ); + uint32_t min_wave_constraints_for_dispatch = param( + &min_wave_constraints_for_dispatch, "jobs.min_wave_constraints_for_dispatch", 512, + {.name = "Min wave constraints per dispatch", + .min = 1, + .max = 65536, + .kind = Kind::advanced, + .description = "Smaller constraint waves solve inline"} + ); + uint32_t min_wave_joints_for_dispatch = param( + &min_wave_joints_for_dispatch, "jobs.min_wave_joints_for_dispatch", 64, + {.name = "Min wave joints per dispatch", + .min = 1, + .max = 65536, + .kind = Kind::advanced, + .description = "Smaller joint waves solve inline"} + ); + uint32_t box_voxel_split_min_voxels = param( + &box_voxel_split_min_voxels, "jobs.box_voxel_split_min_voxels", 500000, + {.name = "Box-voxel split threshold", + .min = 1, + .max = 1000000, + .kind = Kind::advanced, + .description = "Box against voxel pairs this big are split across jobs"} + ); + uint32_t voxel_voxel_split_min_voxels = param( + &voxel_voxel_split_min_voxels, "jobs.voxel_voxel_split_min_voxels", 250000, + {.name = "Voxel-voxel split threshold", + .min = 1, + .max = 1000000, + .kind = Kind::advanced, + .description = "Voxel against voxel pairs this big are split across jobs"} + ); + uint32_t voxel_pair_split_regions = param( + &voxel_pair_split_regions, "jobs.voxel_pair_split_regions", 8, + {.name = "Voxel pair split regions", + .min = 1, + .max = 64, + .kind = Kind::advanced, + .description = "Jobs a split pair is divided into"} + ); + bool time_narrow_pairs = param( + &time_narrow_pairs, "step.time_narrow_pairs", false, + {.name = "Time narrow phase pairs", + .kind = Kind::debug, + .description = "Times each kind of narrow phase pair for the overlay"} + ); + + bool draw_shapes = param( + &draw_shapes, "world.draw_shapes", false, + {.name = "Draw shapes", + .kind = Kind::debug, + .description = "Outlines colliders: green awake, blue asleep, yellow kinematic, grey fixed"} + ); + bool draw_bounds = param( + &draw_bounds, "broadphase.draw_bounds", false, + {.name = "Draw bounds", .kind = Kind::debug, .description = "The box the broad phase tests first"} + ); + bool draw_contacts = param( + &draw_contacts, "solver.draw_contacts", false, + {.name = "Draw contacts", .kind = Kind::debug, .description = "Contact points and the normals they push along"} + ); + bool draw_velocity = param( + &draw_velocity, "world.draw_velocity", false, + {.name = "Draw velocity", .kind = Kind::debug, .description = "An arrow along each awake body's motion"} + ); + bool draw_centers = param( + &draw_centers, "world.draw_centers", false, + {.name = "Draw centers of mass", .kind = Kind::debug, .description = "A dot at each center of mass"} + ); + float velocity_scale = param( + &velocity_scale, "world.velocity_scale", 0.25f, + {.name = "Velocity arrow scale", + .min = 0.01f, + .max = 5.0f, + .unit = "s", + .kind = Kind::debug, + .description = "Seconds of travel an arrow covers"} + ); + float contact_normal_length = param( + &contact_normal_length, "solver.contact_normal_length", 0.3f, + {.name = "Contact normal length", + .min = 0.05f, + .max = 3.0f, + .unit = "m", + .kind = Kind::debug, + .description = "Length of a contact normal"} + ); + uint32_t sweep_refine_iterations = param( + &sweep_refine_iterations, "character.sweep_refine_iterations", 6, + {.name = "Sweep refine iterations", .min = 1, .max = 32, .description = "Refinement steps after a sweep hits something"} + ); + std::vector layer_names = param( + &layer_names, "layers.names", defaultLayerNames(), {.name = "Layer names", .description = "Layer 0 cannot be renamed"} + ); + std::vector layer_abbreviations = param( + &layer_abbreviations, "layers.abbreviations", defaultLayerAbbreviations(), + {.name = "Layer abbreviations", .description = "Up to three characters"} + ); [[nodiscard]] auto fixedDelta() const noexcept -> double { @@ -90,6 +526,8 @@ struct Tunables { } }; +using Tunables = PhysicsParams; + [[nodiscard]] TOAST_API auto tunables() -> const Tunables&; diff --git a/engine/src/toast/physics/simulator.hpp b/engine/src/toast/physics/simulator.hpp index 5c156cee8..1b490099b 100644 --- a/engine/src/toast/physics/simulator.hpp +++ b/engine/src/toast/physics/simulator.hpp @@ -88,6 +88,8 @@ class TOAST_API Simulator { void tick(); void integrate(float dt); + void drawDebugVisuals() const; + [[nodiscard]] auto createBody(const BodyDescriptor& descriptor) -> BodyID; void destroyBody(BodyID body); diff --git a/engine/src/toast/project_settings.cpp b/engine/src/toast/project_settings.cpp index 2457a4524..bb57a9126 100644 --- a/engine/src/toast/project_settings.cpp +++ b/engine/src/toast/project_settings.cpp @@ -1,16 +1,63 @@ #include "project_settings.hpp" +#include "toast/params/files.hpp" +#include "toast/params/project_params.hpp" + #include namespace toast { -ProjectSettings::ProjectSettings(const std::filesystem::path& path) { +namespace detail { + +struct ProjectGroups { + params::ProjectParams project; + params::GameplayParams gameplay; + params::UIParams ui; +}; + +} + +namespace { + +template +auto handleFrom(const params::AssetRef& asset) -> assets::Handle { + const std::string& uri = asset.uri; + if (uri.empty()) { + return {}; + } + return {nullptr, toast::UID::make(), uri}; +} + +} + +ProjectSettings::ProjectSettings(const std::filesystem::path& path, params::Files* files) + : m_groups(std::make_unique()) { ZoneScoped; instance = this; + if (files != nullptr) { + files->load(m_groups->project); + files->load(m_groups->gameplay); + files->load(m_groups->ui); + } + + m_databases = m_groups->project.databases; + if (m_databases.empty()) { + m_databases.emplace_back("assets"); + } + m_max_tick_rate = m_groups->project.max_tick_rate; + + m_gameplay_settings.m_init_scene = handleFrom(m_groups->gameplay.init_scene); + m_gameplay_settings.m_player = handleFrom(m_groups->gameplay.player); + + m_ui_settings.m_color_scheme = handleFrom(m_groups->ui.color_scheme); + m_ui_settings.m_languages = m_groups->ui.languages; + if (m_ui_settings.m_languages.empty()) { + m_ui_settings.m_languages.emplace_back("en"); + } + if (path.empty() || !std::filesystem::exists(path)) { TOAST_WARN("ProjectSettings", "No project file found; using defaults"); - m_databases = {"assets"}; return; } @@ -25,56 +72,18 @@ ProjectSettings::ProjectSettings(const std::filesystem::path& path) { } } - if (auto* dbs = table["databases"].as_array()) { - for (const auto& db : *dbs) { - if (auto str = db.value()) { - m_databases.push_back(*str); - } - } - } - if (m_databases.empty()) { - m_databases.emplace_back("assets"); - } - - m_max_tick_rate = - static_cast(std::max(0, table["max_tick_rate"].value_or(k_default_max_tick_rate))); - - if (auto* gameplay = table["gameplay"].as_table()) { - auto make_handle = [](std::string_view uri) -> assets::Handle { - return {nullptr, toast::UID::make(), uri}; - }; - if (auto uri = (*gameplay)["init_scene"].value()) { - m_gameplay_settings.m_init_scene = make_handle(*uri); - } - if (auto uri = (*gameplay)["player"].value()) { - m_gameplay_settings.m_player = make_handle(*uri); - } - } - - if (auto* ui = table["ui"].as_table()) { - if (auto uri = (*ui)["color_scheme"].value()) { - m_ui_settings.m_color_scheme = {nullptr, toast::UID::make(), *uri}; - } - if (auto* langs = (*ui)["languages"].as_array()) { - m_ui_settings.m_languages.clear(); - for (const auto& lang : *langs) { - if (auto str = lang.value()) { - m_ui_settings.m_languages.push_back(*str); - } - } - } - if (m_ui_settings.m_languages.empty()) { - m_ui_settings.m_languages.emplace_back("en"); - } - } - TOAST_INFO("ProjectSettings", "Loaded '{}' {} — {} database(s)", m_name, version(), m_databases.size()); } catch (const std::exception& e) { TOAST_ERROR("ProjectSettings", "Failed to parse {}: {}; using defaults", path.string(), e.what()); m_name = "Untitled"; m_version = {1, 0, 0}; - m_databases = {"assets"}; + } +} + +ProjectSettings::~ProjectSettings() { + if (instance == this) { + instance = nullptr; } } diff --git a/engine/src/toast/project_settings.hpp b/engine/src/toast/project_settings.hpp index a1aa099ac..92969cb74 100644 --- a/engine/src/toast/project_settings.hpp +++ b/engine/src/toast/project_settings.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -16,6 +17,14 @@ namespace toast { +namespace params { +class Files; +} + +namespace detail { +struct ProjectGroups; +} + class TOAST_API GameplaySettings { public: [[nodiscard]] @@ -60,7 +69,11 @@ class TOAST_API PhysicsSettings { class TOAST_API ProjectSettings { public: - explicit ProjectSettings(const std::filesystem::path& path); + explicit ProjectSettings(const std::filesystem::path& path, params::Files* files = nullptr); + ~ProjectSettings(); + + ProjectSettings(const ProjectSettings&) = delete; + auto operator=(const ProjectSettings&) -> ProjectSettings& = delete; static auto get() -> ProjectSettings* { return instance; } @@ -91,6 +104,7 @@ class TOAST_API ProjectSettings { std::vector m_databases; GameplaySettings m_gameplay_settings; UISettings m_ui_settings; + std::unique_ptr m_groups; }; } diff --git a/engine/src/toast/renderer/passes/debug/console_pass.cpp b/engine/src/toast/renderer/passes/debug/console_pass.cpp new file mode 100644 index 000000000..8d47c7d65 --- /dev/null +++ b/engine/src/toast/renderer/passes/debug/console_pass.cpp @@ -0,0 +1,241 @@ +#include "toast/renderer/passes/debug/console_pass.hpp" + +#include "toast/renderer/core/vulkan_core.hpp" +#include "toast/renderer/vulkan_renderer.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace renderer { +namespace { + +constexpr double k_message_seconds = 2.0; + +auto rectMin(const toast::console::Rect& r) -> ImVec2 { + return {r.x, r.y}; +} + +auto rectMax(const toast::console::Rect& r) -> ImVec2 { + return {r.x + r.w, r.y + r.h}; +} + +auto fitted(ImFont* font, float size, const std::string& text, float width) -> std::string { + const auto measure = [&](const std::string& t) { return font->CalcTextSizeA(size, FLT_MAX, 0.0F, t.c_str()).x; }; + if (measure(text) <= width) { + return text; + } + std::string cut = text; + while (!cut.empty() && measure(cut + "...") > width) { + cut.pop_back(); + while (!cut.empty() && (static_cast(cut.back()) & 0xC0U) == 0x80U) { + cut.pop_back(); + } + } + return cut + "..."; +} + +void draw(const toast::console::View& view, float width, float height) { + using toast::console::EntryKind; + + ImFont* font = ImGui::GetFont(); + const float scale = std::max(1.0F, height / 900.0F); + const float size = std::round(15.0F * scale); + const float line = std::round(size * 1.3F); + + const auto measure = [&](std::string_view text) { + return text.empty() ? 0.0F : font->CalcTextSizeA(size, FLT_MAX, 0.0F, text.data(), text.data() + text.size()).x; + }; + const auto layout = toast::console::layout(view, width, height, line, measure); + ImDrawList* list = ImGui::GetForegroundDrawList(); + const float pad = layout.padding; + const auto text_at = [&](float x, float y, ImU32 c, const std::string& text) { + list->AddText(font, size, ImVec2(x, y + ((line - size) * 0.5F)), c, text.c_str()); + }; + + const ImU32 white = IM_COL32(255, 255, 255, 255); + const ImU32 grey = IM_COL32(170, 170, 170, 255); + const ImU32 strip = IM_COL32(0, 0, 0, 150); + const ImU32 popup = IM_COL32(0, 0, 0, 190); + const ImU32 selected = IM_COL32(255, 255, 255, 60); + + for (size_t i = 0; i < view.pins.size(); ++i) { + const float y = static_cast(i) * line; + list->AddRectFilled(ImVec2(0.0F, y), ImVec2(measure(view.pins[i]) + (2.0F * pad), y + line), strip); + text_at(pad, y, white, view.pins[i]); + } + + if (!view.open) { + if (!view.log.empty() && view.message_age < k_message_seconds) { + const float y = height - line - pad; + list->AddRectFilled(ImVec2(0.0F, y), ImVec2(width, y + line), strip); + text_at(pad, y, white, view.log.back().second); + } + return; + } + + // what the last lines said + for (const auto& log : layout.log) { + const auto& message = view.log[log.line].second; + list->AddRectFilled(rectMin(log.rect), rectMax(log.rect), strip); + text_at(log.rect.x + pad, log.rect.y, white, message); + } + + if (!layout.rows.empty()) { + list->AddRectFilled(rectMin(layout.popup), rectMax(layout.popup), popup); + for (const auto& row : layout.rows) { + const auto& entry = view.completion.entries[row.entry]; + if (row.entry == view.selected) { + list->AddRectFilled(rectMin(row.rect), rectMax(row.rect), selected); + } + + const std::string label = + entry.kind == EntryKind::group || entry.kind == EntryKind::subgroup ? entry.label + "." : entry.label; + text_at(row.rect.x + pad, row.rect.y + (pad * 0.25F), white, label); + + if (!entry.value.empty()) { + const float room = std::max(0.0F, row.rect.w - (3.0F * pad) - measure(label)); + const std::string shown = fitted(font, size, entry.value, room); + text_at(row.rect.x + row.rect.w - pad - measure(shown), row.rect.y + (pad * 0.25F), grey, shown); + } + } + } + + // the line itself + list->AddRectFilled(rectMin(layout.bar), rectMax(layout.bar), strip); + const float text_y = layout.bar.y + pad; + text_at(pad, text_y, white, ">"); + text_at(pad + measure("> "), text_y, white, view.text); + + if (!view.completion.hint.empty()) { + const float room = std::max(0.0F, layout.bar.w - layout.cursor_x - (4.0F * pad)); + const std::string shown = fitted(font, size, view.completion.hint, room); + text_at(layout.bar.x + layout.bar.w - pad - measure(shown), text_y, grey, shown); + } + if (std::fmod(ImGui::GetTime(), 1.0) < 0.6) { + list->AddRectFilled( + ImVec2(layout.cursor_x, text_y + 1.0F), ImVec2(layout.cursor_x + std::max(2.0F, scale), text_y + line - 1.0F), white + ); + } +} + +} + +ConsolePass::ConsolePass(const renderer::VulkanCore& core, vk::Format color_format, vk::Format depth_format) { + ZoneScoped; + IMGUI_CHECKVERSION(); + ImGuiContext* previous = ImGui::GetCurrentContext(); + m_context = ImGui::CreateContext(); + ImGui::SetCurrentContext(m_context); + ImGuiIO& io = ImGui::GetIO(); + io.IniFilename = nullptr; + io.LogFilename = nullptr; + io.BackendPlatformName = "toast_engine (console)"; + io.BackendRendererName = "imgui_impl_vulkan"; + io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange; + io.SetClipboardTextFn = nullptr; + io.GetClipboardTextFn = nullptr; + + constexpr auto k_font = "core://ui/fonts/FiraCodeNerdFont-Regular.ttf"; + if (assets::AssetManager::isInitialized()) { + if (auto bytes = assets::AssetManager::get().tryLoadBytes(k_font); bytes && !bytes->empty()) { + m_font_data = std::move(*bytes); + ImFontConfig config; + config.FontDataOwnedByAtlas = false; + if (io.Fonts->AddFontFromMemoryTTF(m_font_data.data(), static_cast(m_font_data.size()), 0.0F, &config) == nullptr) { + TOAST_WARN("Console", "Could not read the console font"); + m_font_data.clear(); + } + } else { + TOAST_WARN("Console", "{} is missing, using the built in font", k_font); + } + } + + const std::array color_formats {color_format}; + vk::PipelineRenderingCreateInfo rendering_ci {}; + rendering_ci.colorAttachmentCount = 1; + rendering_ci.pColorAttachmentFormats = color_formats.data(); + rendering_ci.depthAttachmentFormat = depth_format; + + ImGui_ImplVulkan_InitInfo init_info {}; + init_info.ApiVersion = VK_API_VERSION_1_4; + init_info.Instance = *core.getInstance(); + init_info.PhysicalDevice = *core.getPhysicalDevice(); + init_info.Device = *core.getDevice(); + init_info.QueueFamily = core.getGraphicsQueueFamilyIndex(); + init_info.Queue = core.getGraphicsQueue(); + init_info.DescriptorPoolSize = 8; + init_info.MinImageCount = 2; + init_info.ImageCount = VulkanRenderer::k_frames_in_flight; + init_info.UseDynamicRendering = true; + init_info.PipelineInfoMain.PipelineRenderingCreateInfo = static_cast(rendering_ci); + + m_ready = ImGui_ImplVulkan_Init(&init_info); + if (!m_ready) { + TOAST_ERROR("Console", "Failed to initialize the ImGui Vulkan backend; the console will not be drawn"); + ImGui::DestroyContext(m_context); + m_context = nullptr; + } + ImGui::SetCurrentContext(previous); +} + +ConsolePass::~ConsolePass() { + if (m_ready) { + ImGui::SetCurrentContext(m_context); + ImGui_ImplVulkan_Shutdown(); + ImGui::DestroyContext(m_context); + } +} + +void ConsolePass::update(uint32_t frame_index, float dt) { + ZoneScoped; + (void)frame_index; + m_drawing = false; + if (!m_ready) { + return; + } + + const toast::console::View view = toast::console::Console::get().view(); + const bool showing_message = !view.open && !view.log.empty() && view.message_age < k_message_seconds; + if (!view.open && !showing_message && view.pins.empty()) { + return; + } + const auto* frame = VulkanRenderer::instance->renderingFrame(); + if (frame == nullptr || frame->output_extent.x < 1.0F || frame->output_extent.y < 1.0F) { + return; + } + + ImGui::SetCurrentContext(m_context); + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize = ImVec2(frame->output_extent.x, frame->output_extent.y); + io.DeltaTime = std::max(dt, 0.0001F); + + ImGui_ImplVulkan_NewFrame(); + ImGui::NewFrame(); + draw(view, frame->output_extent.x, frame->output_extent.y); + ImGui::Render(); + m_drawing = true; +} + +void ConsolePass::record(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t image_index) { + ZoneScoped; + (void)frame_index; + (void)image_index; + if (!m_ready || !m_drawing) { + return; + } + ImGui::SetCurrentContext(m_context); + if (ImDrawData* draw_data = ImGui::GetDrawData(); draw_data != nullptr) { + ImGui_ImplVulkan_RenderDrawData(draw_data, cmd); + } +} + +} diff --git a/engine/src/toast/renderer/passes/debug/console_pass.hpp b/engine/src/toast/renderer/passes/debug/console_pass.hpp new file mode 100644 index 000000000..61f24537d --- /dev/null +++ b/engine/src/toast/renderer/passes/debug/console_pass.hpp @@ -0,0 +1,40 @@ +#pragma once +#include "toast/renderer/core/vulkan_common.hpp" +#include "toast/renderer/passes/render_pass_base.hpp" + +#include + +struct ImGuiContext; + +namespace renderer { +class VulkanCore; + +class ConsolePass : public IRenderPass { +public: + ConsolePass(const renderer::VulkanCore& core, vk::Format color_format, vk::Format depth_format); + ~ConsolePass() override; + + ConsolePass(const ConsolePass&) = delete; + auto operator=(const ConsolePass&) -> ConsolePass& = delete; + + [[nodiscard]] + auto stage() const -> RenderStage override { + return RenderStage::overlay; + } + + void update(uint32_t frame_index, float dt) override; + void record(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t image_index) override; + + [[nodiscard]] + auto name() const -> std::string_view override { + return "Console"; + } + +private: + ImGuiContext* m_context = nullptr; + std::vector m_font_data; + bool m_ready = false; + bool m_drawing = false; +}; + +} diff --git a/engine/src/toast/renderer/passes/debug/debug_pass.cpp b/engine/src/toast/renderer/passes/debug/debug_pass.cpp index 07bf900bf..98acaf86e 100644 --- a/engine/src/toast/renderer/passes/debug/debug_pass.cpp +++ b/engine/src/toast/renderer/passes/debug/debug_pass.cpp @@ -308,8 +308,9 @@ DebugPass::DebugPass( DebugPass::~DebugPass() { if (m_imgui_ready) { + ImGui::SetCurrentContext(m_imgui_context); ImGui_ImplVulkan_Shutdown(); - ImGui::DestroyContext(); + ImGui::DestroyContext(m_imgui_context); } } @@ -398,6 +399,7 @@ void DebugPass::update(uint32_t frame_index, float dt) { } if (m_imgui_ready) { + ImGui::SetCurrentContext(m_imgui_context); ImGuiIO& io = ImGui::GetIO(); const auto& input = frame->imgui_input; @@ -1181,6 +1183,7 @@ void DebugPass::record(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t ima } if (m_imgui_ready) { + ImGui::SetCurrentContext(m_imgui_context); ImDrawData* draw_data = ImGui::GetDrawData(); if (draw_data != nullptr) { ImGui_ImplVulkan_RenderDrawData(draw_data, cmd); @@ -1327,7 +1330,9 @@ auto DebugPass::billboardTextureSet(const renderer::VulkanCore& core, vk::ImageV void DebugPass::initImGui(const renderer::VulkanCore& core, vk::Format color_format, vk::Format depth_format) { ZoneScoped; IMGUI_CHECKVERSION(); - ImGui::CreateContext(); + ImGuiContext* previous = ImGui::GetCurrentContext(); + m_imgui_context = ImGui::CreateContext(); + ImGui::SetCurrentContext(m_imgui_context); ImGuiIO& io = ImGui::GetIO(); io.BackendPlatformName = "toast_engine (manual input feed)"; io.BackendRendererName = "imgui_impl_vulkan"; @@ -1360,8 +1365,9 @@ void DebugPass::initImGui(const renderer::VulkanCore& core, vk::Format color_for m_imgui_ready = ImGui_ImplVulkan_Init(&init_info); if (!m_imgui_ready) { TOAST_ERROR("DebugPass", "Failed to initialize ImGui Vulkan backend"); - ImGui::DestroyContext(); + ImGui::DestroyContext(m_imgui_context); } + ImGui::SetCurrentContext(previous); } void DebugPass::createGizmoGeometry(const renderer::VulkanCore& core) { diff --git a/engine/src/toast/renderer/passes/debug/debug_pass.hpp b/engine/src/toast/renderer/passes/debug/debug_pass.hpp index 94d95108e..685351512 100644 --- a/engine/src/toast/renderer/passes/debug/debug_pass.hpp +++ b/engine/src/toast/renderer/passes/debug/debug_pass.hpp @@ -16,6 +16,8 @@ #include #include +struct ImGuiContext; + namespace renderer { class VulkanCore; class ClusterLightingPass; @@ -131,6 +133,7 @@ class DebugPass : public IRenderPass { std::unordered_map m_billboard_texture_sets; bool m_imgui_ready = false; + ImGuiContext* m_imgui_context = nullptr; bool m_editor_panels = true; /// Last io.WantCapture* sent to the input system diff --git a/engine/src/toast/renderer/passes/debug/perf_window.cpp b/engine/src/toast/renderer/passes/debug/perf_window.cpp index 8c9cf10e3..4056c7e33 100644 --- a/engine/src/toast/renderer/passes/debug/perf_window.cpp +++ b/engine/src/toast/renderer/passes/debug/perf_window.cpp @@ -21,7 +21,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -52,99 +53,114 @@ enum class PerfLevel : uint8_t { /// Queued ahead of an edit so Custom starts from the tier void requestCustomPreset() { - auto& registry = toast::settings::Settings::get(); - if (const toast::settings::Entry* preset = registry.find("renderer.quality.preset"); preset != nullptr) { - VulkanRenderer::instance->requestSettingValue(preset->key, static_cast(preset->meta.options.size()) - 1); + if (const toast::params::ParamBase* preset = toast::params::Registry::get().find("renderer.quality.preset"); + preset != nullptr) { + VulkanRenderer::instance->requestSettingValue( + "renderer.quality.preset", + toast::params::Value {toast::params::Scalar {static_cast(preset->options().size()) - 1}} + ); } } +auto pathOf(const toast::params::ParamBase& param) -> std::string { + return std::string {param.group()->name()} + "." + std::string {param.id()}; +} + /// An edit of a preset_driven row switches to Custom -void drawSettingRow(toast::settings::Entry* entry, bool preset_driven = false) { - using toast::settings::Type; - using toast::settings::Value; +void drawSettingRow(toast::params::ParamBase* param, bool preset_driven = false) { + using toast::params::Scalar; + using toast::params::Type; + using toast::params::Value; - auto& registry = toast::settings::Settings::get(); - ImGui::PushID(entry->key.c_str()); + const std::string path = pathOf(*param); + ImGui::PushID(path.c_str()); ImGui::TableNextRow(); ImGui::TableNextColumn(); - std::string_view label = entry->meta.label; - if (label.empty()) { - label = std::string_view(entry->key).substr(entry->key.rfind('.') + 1); - } + const std::string label {param->name()}; ImGui::AlignTextToFramePadding(); - ImGui::TextUnformatted(label.data(), label.data() + label.size()); - if (ImGui::IsItemHovered() && !entry->meta.description.empty()) { - ImGui::SetTooltip("%s%s", entry->meta.description.c_str(), entry->meta.requires_restart ? "\nApplies on restart" : ""); + ImGui::TextUnformatted(label.c_str()); + if (ImGui::IsItemHovered() && !param->description().empty()) { + ImGui::SetTooltip("%s%s", std::string {param->description()}.c_str(), param->requiresRestart() ? "\nApplies on restart" : ""); } - if (entry->meta.requires_restart) { + if (param->requiresRestart()) { ImGui::SameLine(); ImGui::TextColored(k_perf_warn, "(restart)"); } ImGui::TableNextColumn(); ImGui::SetNextItemWidth(-FLT_MIN); - Value value = registry.resolved(entry); + Value value = param->snapshot(); bool leaves_tier = false; if (preset_driven) { - if (auto forced = presetDrivenValue(entry->key); forced.has_value()) { + if (auto forced = presetDrivenValue(path); forced.has_value()) { value = std::move(*forced); leaves_tier = true; } } - const bool bounded = entry->meta.min < entry->meta.max; + const Scalar* scalar = std::get_if(&value); + const auto min = param->minValue(); + const auto max = param->maxValue(); std::optional changed; - switch (entry->type) { - case Type::boolean: { - bool current = std::get(value); - if (ImGui::Checkbox("##value", ¤t)) { - changed = current; + if (scalar == nullptr) { + ImGui::TextDisabled("array"); + } else { + switch (param->type()) { + case Type::boolean: { + bool current = std::get(*scalar); + if (ImGui::Checkbox("##value", ¤t)) { + changed = Value {Scalar {current}}; + } + break; } - break; - } - case Type::integer: { - int64_t current = std::get(value); - const auto& options = entry->meta.options; - if (!options.empty()) { - const auto index = static_cast(std::clamp(current, 0, static_cast(options.size()) - 1)); - if (ImGui::BeginCombo("##value", options[index].c_str())) { - for (size_t i = 0; i < options.size(); ++i) { - if (ImGui::Selectable(options[i].c_str(), i == index)) { - changed = static_cast(i); + case Type::integer: { + int64_t current = std::get(*scalar); + const auto options = param->options(); + if (!options.empty()) { + const auto index = static_cast(std::clamp(current, 0, static_cast(options.size()) - 1)); + if (ImGui::BeginCombo("##value", std::string {options[index]}.c_str())) { + for (size_t i = 0; i < options.size(); ++i) { + if (ImGui::Selectable(std::string {options[i]}.c_str(), i == index)) { + changed = Value {Scalar {static_cast(i)}}; + } } + ImGui::EndCombo(); } - ImGui::EndCombo(); + break; + } + const bool bounded = min && max; + const int64_t low = bounded ? std::get(*min) : 0; + const int64_t high = bounded ? std::get(*max) : 0; + const bool edited = bounded ? ImGui::SliderScalar("##value", ImGuiDataType_S64, ¤t, &low, &high) + : ImGui::DragScalar("##value", ImGuiDataType_S64, ¤t); + if (edited) { + changed = Value {Scalar {current}}; } break; } - const auto low = static_cast(entry->meta.min); - const auto high = static_cast(entry->meta.max); - const bool edited = bounded ? ImGui::SliderScalar("##value", ImGuiDataType_S64, ¤t, &low, &high) - : ImGui::DragScalar("##value", ImGuiDataType_S64, ¤t); - if (edited) { - changed = current; - } - break; - } - case Type::floating: { - double current = std::get(value); - const double low = entry->meta.min; - const double high = entry->meta.max; - const auto speed = static_cast(entry->meta.step > 0.0 ? entry->meta.step : 0.01); - const bool edited = bounded ? ImGui::SliderScalar("##value", ImGuiDataType_Double, ¤t, &low, &high, "%.3g") - : ImGui::DragScalar("##value", ImGuiDataType_Double, ¤t, speed, nullptr, nullptr, "%.3g"); - if (edited) { - changed = current; + case Type::floating: { + double current = std::get(*scalar); + const bool bounded = min && max; + const double low = bounded ? std::get(*min) : 0.0; + const double high = bounded ? std::get(*max) : 0.0; + const bool edited = bounded + ? ImGui::SliderScalar("##value", ImGuiDataType_Double, ¤t, &low, &high, "%.3g") + : ImGui::DragScalar("##value", ImGuiDataType_Double, ¤t, 0.01f, nullptr, nullptr, "%.3g"); + if (edited) { + changed = Value {Scalar {current}}; + } + break; } - break; + case Type::string: ImGui::TextDisabled("%s", std::get(*scalar).c_str()); break; + case Type::asset: ImGui::TextDisabled("%s", std::get(*scalar).uri.c_str()); break; + default: ImGui::TextDisabled("%s", toast::params::toText(value, param->type()).c_str()); break; } - case Type::string: ImGui::TextDisabled("%s", std::get(value).c_str()); break; } if (changed.has_value()) { if (leaves_tier) { requestCustomPreset(); } - VulkanRenderer::instance->requestSettingValue(entry->key, *changed); + VulkanRenderer::instance->requestSettingValue(path, *changed); } ImGui::PopID(); } @@ -1007,8 +1023,6 @@ void PerfWindow::drawSceneTab() { } void PerfWindow::drawShadowsTab() { - using toast::settings::Entry; - if (const auto* frame = VulkanRenderer::instance->renderingFrame(); frame != nullptr) { const auto& lights = frame->light_stats; const auto slots = [](const char* label, uint32_t used, uint32_t budget, uint32_t denied) { @@ -1028,14 +1042,14 @@ void PerfWindow::drawShadowsTab() { ImGui::TextDisabled("Nearest lights win. Raise a budget or lower Shadow Distance on lights that need none"); } - auto& registry = toast::settings::Settings::get(); ImGui::SeparatorText("Settings"); if (ImGui::BeginTable("##perf_shadow_settings", 2, ImGuiTableFlags_SizingStretchProp)) { - for (Entry* entry : registry.entries()) { - if (entry->meta.hidden || !entry->key.starts_with("renderer.shadows.")) { - continue; + if (const toast::params::GroupBase* group = toast::params::Registry::get().findGroup("renderer"); group != nullptr) { + for (toast::params::ParamBase* param : group->params()) { + if (param->id().starts_with("shadows.")) { + drawSettingRow(param); + } } - drawSettingRow(entry); } ImGui::EndTable(); } @@ -1043,13 +1057,13 @@ void PerfWindow::drawShadowsTab() { } void PerfWindow::drawQualityTab() { - auto& registry = toast::settings::Settings::get(); + auto& registry = toast::params::Registry::get(); const auto rows = [®istry](const char* id, std::initializer_list keys, bool preset_driven = false) { if (!ImGui::BeginTable(id, 2, ImGuiTableFlags_SizingStretchProp)) { return; } for (const std::string_view key : keys) { - if (toast::settings::Entry* entry = registry.find(key); entry != nullptr) { + if (toast::params::ParamBase* entry = registry.find(key); entry != nullptr) { drawSettingRow(entry, preset_driven); } } @@ -1067,8 +1081,8 @@ void PerfWindow::drawQualityTab() { const bool hdr_active = VulkanRenderer::instance->hdrOutput(); ImGui::TextColored(hdr_active ? k_perf_good : k_perf_warn, "HDR output %s", hdr_active ? "on" : "off"); rows("##perf_display_hdr", {"renderer.display.hdr", "renderer.display.hdr_paper_white", "renderer.display.hdr_peak"}); - if (const toast::settings::Entry* hdr_setting = registry.find("renderer.display.hdr"); hdr_setting != nullptr) { - const bool wanted = std::get(registry.resolved(hdr_setting)); + if (const toast::params::ParamBase* hdr_setting = registry.find("renderer.display.hdr"); hdr_setting != nullptr) { + const bool wanted = std::get(std::get(hdr_setting->snapshot())); if (wanted && !hdr_active) { ImGui::PushStyleColor(ImGuiCol_Text, k_perf_warn); ImGui::TextWrapped("SDR is in use. Turn HDR on for this display"); @@ -1080,9 +1094,9 @@ void PerfWindow::drawQualityTab() { } } - const toast::settings::Entry* preset = registry.find("renderer.quality.preset"); - const size_t tier_count = preset != nullptr ? preset->meta.options.size() - 1 : 0; - const int64_t preset_value = preset != nullptr ? std::get(registry.resolved(preset)) : 0; + const toast::params::ParamBase* preset = registry.find("renderer.quality.preset"); + const size_t tier_count = preset != nullptr ? preset->options().size() - 1 : 0; + const int64_t preset_value = preset != nullptr ? std::get(std::get(preset->snapshot())) : 0; const bool custom = preset == nullptr || std::cmp_greater_equal(preset_value, tier_count); const bool rt_tier = !custom && std::cmp_greater_equal(preset_value, tier_count / 2); @@ -1102,27 +1116,34 @@ void PerfWindow::drawQualityTab() { } // On release since each value recreates every target - if (toast::settings::Entry* scale = registry.find("renderer.quality.render_scale"); + if (toast::params::ParamBase* scale = registry.find("renderer.quality.render_scale"); scale != nullptr && ImGui::BeginTable("##perf_quality_scale", 2, ImGuiTableFlags_SizingStretchProp)) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::AlignTextToFramePadding(); - ImGui::TextUnformatted(scale->meta.label.c_str()); + ImGui::TextUnformatted(std::string {scale->name()}.c_str()); ImGui::TableNextColumn(); ImGui::SetNextItemWidth(-FLT_MIN); - const auto forced_scale = presetDrivenValue(scale->key); + const auto forced_scale = presetDrivenValue("renderer.quality.render_scale"); if (!m_render_scale_editing) { - m_render_scale_edit = static_cast(std::get(forced_scale.value_or(registry.resolved(scale)))); + m_render_scale_edit = + static_cast(std::get(std::get(forced_scale.value_or(scale->snapshot())))); } ImGui::SliderFloat( - "##value", &m_render_scale_edit, static_cast(scale->meta.min), static_cast(scale->meta.max), "%.2f" + "##value", + &m_render_scale_edit, + static_cast(std::get(*scale->minValue())), + static_cast(std::get(*scale->maxValue())), + "%.2f" ); m_render_scale_editing = ImGui::IsItemActive(); if (ImGui::IsItemDeactivatedAfterEdit()) { if (forced_scale.has_value()) { requestCustomPreset(); } - VulkanRenderer::instance->requestSettingValue(scale->key, static_cast(m_render_scale_edit)); + VulkanRenderer::instance->requestSettingValue( + "renderer.quality.render_scale", toast::params::Value {toast::params::Scalar {static_cast(m_render_scale_edit)}} + ); } ImGui::EndTable(); diff --git a/engine/src/toast/renderer/resources/video_textures.cpp b/engine/src/toast/renderer/resources/video_textures.cpp index 1e25d6739..5a01cec10 100644 --- a/engine/src/toast/renderer/resources/video_textures.cpp +++ b/engine/src/toast/renderer/resources/video_textures.cpp @@ -2,6 +2,7 @@ #include "toast/renderer/resources/video_decoder.hpp" #include "toast/renderer/resources/vulkan_texture.hpp" +#include "toast/renderer/settings/renderer_params.hpp" #include "toast/renderer/vulkan_renderer.hpp" #include @@ -15,7 +16,6 @@ #include #include #include -#include #include #include #include @@ -102,12 +102,7 @@ auto registry() -> Registry& { } auto cacheBudgetBytes() -> size_t { - int64_t megabytes = 512; - if (const auto value = toast::settings::Settings::get().value("renderer.video.frame_cache_mb")) { - if (const auto* v = std::get_if(&*value)) { - megabytes = *v; - } - } + const int64_t megabytes = rendererParams().video_frame_cache_mb; return megabytes > 0 ? static_cast(megabytes) << 20 : 0; } diff --git a/engine/src/toast/renderer/settings/renderer_params.hpp b/engine/src/toast/renderer/settings/renderer_params.hpp new file mode 100644 index 000000000..d85e94d81 --- /dev/null +++ b/engine/src/toast/renderer/settings/renderer_params.hpp @@ -0,0 +1,621 @@ +/** + * @file renderer_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Every renderer setting + */ + +#pragma once +#include "toast/renderer/lighting/shadow_constants.hpp" +#include "toast/renderer/lighting/shadow_slots.hpp" + +#include +#include +#include +#include +#include +#include + +namespace renderer { + +namespace options { +inline constexpr std::array view_mode { + "Lit", + "ClusterHeatmap", + "Albedo", + "Normal", + "MetallicRoughness", + "Ambient", + "SpecularIbl", + "SpecularIblMip0", + "Reflection", + "ReflectionProbes", + "ProbeCapture", + "ProbeCubemap", + "NormalBuffer", + "RoughnessBuffer", + "SsrOnly", + "AmbientOcclusion", + "IrradianceVolumes", + "TracedShadowsOnly", + "TracedShadows", + "ShadowTerm", + "VoxelSteps", + "VoxelTraversal", + "VoxelBricks", + "VoxelVolumes", + "VoxelMaterials", + "VoxelPaletteId", + "MotionVectors" +}; +inline constexpr std::array quality_preset { + "Low", "Medium", "High", "Epic", "Low RT", "Medium RT", "High RT", "Epic RT", "Custom" +}; +inline constexpr std::array shadows_cascade_resolution {"256", "512", "1024", "2048", "4096"}; +inline constexpr std::array shadows_punctual_resolution {"256", "512", "1024", "2048", "4096"}; +inline constexpr std::array volumetrics_quality {"Low", "Medium", "High", "Epic", "Custom"}; +inline constexpr std::array volumetrics_resolution {"Half", "Quarter"}; +inline constexpr std::array quality_ray_tracing {"Auto", "On", "Off"}; +inline constexpr std::array antialiasing {"TAA", "DLSS"}; +inline constexpr std::array gi_quality {"Low", "Medium", "High", "Epic", "Custom"}; +inline constexpr std::array gi_clip_resolution {"64", "128", "192"}; +inline constexpr std::array gi_clip_debug_view { + "Off", "Level 0", "Level 1", "Level 2", "Level 3", "Level 4", "Level 5" +}; +inline constexpr std::array gi_clip_debug_mode {"Albedo", "Emission", "Opacity", "Radiance"}; +} + +#if defined(TOAST_DEV_TOOLS) +inline constexpr int64_t k_default_preset = 8; +#else +inline constexpr int64_t k_default_preset = 1; +#endif + +struct RendererParams : toast::params::Group<"renderer"> { + using Kind = toast::params::Kind; + using AssetRef = toast::params::AssetRef; + + bool display_clamp_to_simulation = param( + &display_clamp_to_simulation, "display.clamp_to_simulation", true, + {.name = "Clamp to game thread", + .description = "Wait for a new game frame instead of drawing the same one again. Off runs the GPU flat out"} + ); + bool display_low_latency = param( + &display_low_latency, "display.low_latency", true, + {.name = "Low latency", + .description = "Wait for the GPU to finish a frame before starting the next, so input reaches the screen sooner"} + ); + double display_frame_rate_limit = param( + &display_frame_rate_limit, "display.frame_rate_limit", 0.0, + {.name = "Frame rate limit", .min = 0.0, .max = 360.0, .unit = "fps", .description = "Frames per second. 0 is uncapped"} + ); + double display_hdr_paper_white = param( + &display_hdr_paper_white, "display.hdr_paper_white", 0.0, + {.name = "HDR paper white", + .min = 0.0, + .max = 500.0, + .unit = "nits", + .description = "Nits of SDR white and the UI in HDR. 0 follows the Windows slider"} + ); + double display_hdr_peak = param( + &display_hdr_peak, "display.hdr_peak", 0.0, + {.name = "HDR peak brightness", + .min = 0.0, + .max = 4000.0, + .unit = "nits", + .description = "Nits highlights roll off toward in HDR. 0 asks the display"} + ); + int64_t quality_preset = param( + &quality_preset, "quality.preset", k_default_preset, + {.name = "Preset", + .description = "Sets the quality settings together. Custom uses each one", + .options = options::quality_preset} + ); + double quality_render_scale = param( + &quality_render_scale, "quality.render_scale", 1.0, + {.name = "Render scale", + .min = 0.1, + .max = 1.0, + .description = "Share of the screen resolution the world renders at. Presets cap it at 0.67 (DLSS Quality) on a " + "laptop GPU with DLSS. Custom preset only"} + ); + bool quality_bloom = + param(&quality_bloom, "quality.bloom", true, {.name = "Bloom", .description = "Glow around bright highlights"}); + bool quality_lens_flare = param( + &quality_lens_flare, "quality.lens_flare", true, + {.name = "Lens flare", .description = "Ghosts and streaks from the brightest pixels"} + ); + double quality_glass_glow_scale = param( + &quality_glass_glow_scale, "quality.glass_glow_scale", 1.0, + {.name = "Emissive behind glass", + .min = 0.0, + .max = 16.0, + .description = "How much of the light behind glass bloom and flares still see. 1 is as if the glass was not there"} + ); + bool quality_ssr = + param(&quality_ssr, "quality.ssr", true, {.name = "SSR", .description = "Screen space reflections. Custom preset only"}); + bool quality_ssao = param( + &quality_ssao, "quality.ssao", true, {.name = "SSAO", .description = "Contact shadows in creases. Custom preset only"} + ); + bool quality_motion_blur = param( + &quality_motion_blur, "quality.motion_blur", false, + {.name = "Motion blur", .description = "Blur along motion. Custom preset only"} + ); + double quality_motion_blur_strength = param( + &quality_motion_blur_strength, "quality.motion_blur_strength", 0.5, + {.name = "Motion blur shutter", + .min = 0.0, + .max = 1.0, + .description = "How much of the frame the shutter is open. 0.5 is a 180 degree shutter"} + ); + double quality_motion_blur_max_length = param( + &quality_motion_blur_max_length, "quality.motion_blur_max_length", 0.04, + {.name = "Motion blur max length", .min = 0.005, .max = 0.2, .description = "Longest blur, as a share of the screen height"} + ); + int64_t quality_motion_blur_samples = param( + &quality_motion_blur_samples, "quality.motion_blur_samples", 12, + {.name = "Motion blur samples", .min = 4, .max = 32, .description = "Taps per blur. More is smoother and slower"} + ); + double quality_ssr_reach = param( + &quality_ssr_reach, "quality.ssr_reach", 0.0, + {.name = "SSR reach", + .min = 0.0, + .max = 500.0, + .unit = "m", + .description = "Farthest an SSR ray travels. Custom preset only"} + ); + int64_t quality_ssr_steps = param( + &quality_ssr_steps, "quality.ssr_steps", 0, + {.name = "SSR steps", + .min = 0, + .max = 256, + .description = "Steps per SSR ray. 0 uses the post process volume. Custom preset only"} + ); + bool quality_fxaa = + param(&quality_fxaa, "quality.fxaa", true, {.name = "FXAA", .description = "Cheap edge smoothing. Off while TAA is on"}); + bool quality_taa = + param(&quality_taa, "quality.taa", true, {.name = "TAA", .description = "Smooths edges over several frames"}); + int64_t quality_antialiasing = param( + &quality_antialiasing, "quality.antialiasing", 1, + {.name = "Anti-aliasing", + .description = "DLSS on NVIDIA RTX GPUs, TAA everywhere else. Needs TAA on", + .options = options::antialiasing} + ); + double quality_taa_history = param( + &quality_taa_history, "quality.taa_history", 0.9, + {.name = "TAA history", + .min = 0.5, + .max = 0.98, + .description = "How much of the last frame each pixel keeps. More is smoother and ghosts more"} + ); + bool quality_traced_shadows = param( + &quality_traced_shadows, "quality.traced_shadows", false, + {.name = "Traced shadows", .description = "Trace shadow rays instead of reading shadow maps. Needs ray queries"} + ); + int64_t shadows_cascade_resolution = param( + &shadows_cascade_resolution, "shadows.cascade_resolution", 2, + {.name = "Cascade resolution", + .unit = "px", + .description = "Size of each cascade's shadow map", + .options = options::shadows_cascade_resolution, + .requires_restart = true} + ); + int64_t shadows_punctual_resolution = param( + &shadows_punctual_resolution, "shadows.punctual_resolution", 1, + {.name = "Punctual resolution", + .unit = "px", + .description = "Size of spot and point shadow maps", + .options = options::shadows_punctual_resolution, + .requires_restart = true} + ); + double shadows_distance = param( + &shadows_distance, "shadows.distance", shadows::k_shadow_distance, + {.name = "Shadow distance", + .min = 10.0, + .max = 1000.0, + .unit = "m", + .description = "How far from the camera directional shadows reach"} + ); + double shadows_slot_retention = param( + &shadows_slot_retention, "shadows.slot_retention", shadow_slots::k_default_retention, + {.name = "Slot retention", + .min = 1.0, + .max = 4.0, + .kind = Kind::advanced, + .description = "How much more a light must matter to take another's shadow slot"} + ); + int64_t shadows_slot_grace = param( + &shadows_slot_grace, "shadows.slot_grace", shadow_slots::k_default_grace_frames, + {.name = "Slot grace", + .min = 0, + .max = 300, + .unit = "frames", + .kind = Kind::advanced, + .description = "Frames a light keeps its slot after leaving view"} + ); + int64_t shadows_spot_slots = param( + &shadows_spot_slots, "shadows.spot_slots", shadows::k_default_spot_shadows, + {.name = "Spot shadow slots", + .min = 0, + .max = static_cast(shadows::k_max_spot_shadows), + .description = "Spot lights that can hold a shadow, about 3 MB each at 512", + .requires_restart = true} + ); + int64_t shadows_point_slots = param( + &shadows_point_slots, "shadows.point_slots", shadows::k_default_point_shadows, + {.name = "Point shadow slots", + .min = 0, + .max = static_cast(shadows::k_max_point_shadows), + .description = "Point lights that can hold a shadow, about 18 MB each at 512", + .requires_restart = true} + ); + int64_t shadows_spot_budget = param( + &shadows_spot_budget, "shadows.spot_budget", shadows::k_max_spot_shadows, + {.name = "Spot lights casting", + .min = 0, + .max = static_cast(shadows::k_max_spot_shadows), + .description = "Spot shadows used at once, nearest first"} + ); + int64_t shadows_point_budget = param( + &shadows_point_budget, "shadows.point_budget", shadows::k_max_point_shadows, + {.name = "Point lights casting", + .min = 0, + .max = static_cast(shadows::k_max_point_shadows), + .description = "Point shadows used at once, nearest first"} + ); + double shadows_full_resolution_ranges = param( + &shadows_full_resolution_ranges, "shadows.full_resolution_ranges", shadows::k_punctual_full_resolution_ranges, + {.name = "Full resolution reach", + .min = 0.5, + .max = 16.0, + .kind = Kind::advanced, + .description = "Distance, in light ranges, at which a shadow map starts to shrink"} + ); + double shadows_cascade_split_lambda = param( + &shadows_cascade_split_lambda, "shadows.cascade_split_lambda", shadows::k_cascade_split_lambda, + {.name = "Cascade split", .min = 0.0, .max = 1.0, .description = "0 splits the cascades evenly, 1 logarithmically"} + ); + double shadows_cascade_padding = param( + &shadows_cascade_padding, "shadows.cascade_padding", shadows::k_cascade_padding, + {.name = "Cascade padding", + .min = 0.0, + .max = 0.5, + .description = "Extra margin per cascade, so it re-renders less while the camera moves"} + ); + double shadows_cascade_receiver_depth = param( + &shadows_cascade_receiver_depth, "shadows.cascade_receiver_depth", shadows::k_cascade_receiver_depth_radii, + {.name = "Cascade receiver depth", + .min = 1.0, + .max = 16.0, + .kind = Kind::advanced, + .description = "How far along the light each cascade reaches, in cascade radii"} + ); + bool shadows_static_cache = param( + &shadows_static_cache, "shadows.static_cache", true, + {.name = "Static caster cache", .description = "Cache resting voxel volumes in the shadow map"} + ); + double shadows_caster_tolerance = param( + &shadows_caster_tolerance, "shadows.caster_tolerance", shadows::k_caster_tolerance, + {.name = "Caster tolerance", + .min = 0.0, + .max = 0.1, + .unit = "m", + .description = "How far a voxel volume drifts before its shadow follows"} + ); + bool shadows_voxel_mesh_shaders = param( + &shadows_voxel_mesh_shaders, "shadows.voxel_mesh_shaders", true, + {.name = "Mesh shader voxel casters", .description = "Draw voxel shadow casters with mesh shaders when the GPU has them"} + ); + int64_t voxels_light_candidates = param( + &voxels_light_candidates, "voxels.light_candidates", 8, + {.name = "Light candidates", + .min = 1, + .max = 32, + .kind = Kind::advanced, + .description = "Lights sampled per pixel for marched voxel shadows"} + ); + bool voxels_shadow_maps_only = param( + &voxels_shadow_maps_only, "voxels.shadow_maps_only", false, + {.name = "Shadow maps only", .description = "Voxels use shadow maps for every light. Custom preset only"} + ); + bool voxels_ambient_rays = param( + &voxels_ambient_rays, "voxels.ambient_rays", true, + {.name = "Ambient rays", .description = "Ambient occlusion from rays instead of SSAO on voxels"} + ); + bool voxels_ambient_ray_query = param( + &voxels_ambient_ray_query, "voxels.ambient_ray_query", true, + {.name = "Ray query ambient rays", + .kind = Kind::advanced, + .description = "Use ray queries for ambient rays when the GPU has them"} + ); + double voxels_ambient_reach = param( + &voxels_ambient_reach, "voxels.ambient_reach", 2.4, + {.name = "Ambient reach", + .min = 0.2, + .max = 20.0, + .unit = "m", + .description = "How far an ambient ray looks before it counts as open sky"} + ); + bool voxels_traced_specular = param( + &voxels_traced_specular, "voxels.traced_specular", true, + {.name = "Traced specular", .description = "Trace reflections on shiny voxels instead of the environment and SSR"} + ); + double voxels_specular_roughness = param( + &voxels_specular_roughness, "voxels.specular_roughness", 0.6, + {.name = "Traced specular roughness", + .min = 0.0, + .max = 1.0, + .description = "Rougher voxels keep the environment reflection"} + ); + double voxels_specular_reach = param( + &voxels_specular_reach, "voxels.specular_reach", 32.0, + {.name = "Traced specular reach", .min = 1.0, .max = 200.0, .unit = "m", .description = "How far a reflection ray travels"} + ); + bool voxels_specular_hit_lights = param( + &voxels_specular_hit_lights, "voxels.specular_hit_lights", true, + {.name = "Traced specular hit lights", + .description = "Reflection hits off screen are lit by local lights. Custom preset only"} + ); + int64_t voxels_glass_lit_surfaces = param( + &voxels_glass_lit_surfaces, "voxels.glass_lit_surfaces", 4, + {.name = "Glass lit surfaces", + .min = 1, + .max = 4, + .description = "Glass layers per pixel that get full lighting and reflections"} + ); + double voxels_glass_reflection_reach = param( + &voxels_glass_reflection_reach, "voxels.glass_reflection_reach", 32.0, + {.name = "Glass reflection reach", .min = 0.0, .max = 128.0, .unit = "m", .description = "How far glass reflections reach"} + ); + double voxels_glass_coarse_distance = param( + &voxels_glass_coarse_distance, "voxels.glass_coarse_distance", 30.0, + {.name = "Glass coarse shading distance", + .min = 0.0, + .max = 500.0, + .unit = "m", + .description = "Past this distance glass shades one sample per 2x2 pixels. 0 shades every pixel"} + ); + bool voxels_glass_shadows = param( + &voxels_glass_shadows, "voxels.glass_shadows", true, + {.name = "Glass shadows", .description = "Glass tints the light that reaches voxels behind it"} + ); + int64_t voxels_glass_shadow_reach = param( + &voxels_glass_shadow_reach, "voxels.glass_shadow_reach", 50, + {.name = "Glass shadow reach", + .min = 1, + .max = 2000, + .unit = "m", + .description = "How far a sun looks for glass above a voxel"} + ); + int64_t voxels_sun_reach = param( + &voxels_sun_reach, "voxels.sun_reach", 200, + {.name = "Sun ray reach", .min = 10, .max = 2000, .unit = "m", .description = "How far a marched sun shadow ray travels"} + ); + AssetRef voxels_detail_texture = param( + &voxels_detail_texture, "voxels.detail_texture", AssetRef {}, + {.name = "Voxel detail texture", + .description = "Detail texture the voxel palette reads. None keeps the neutral one", + .asset_type = "detail_texture"} + ); + bool voxels_trace_bricks = param( + &voxels_trace_bricks, "voxels.trace_bricks", true, + {.name = "Brick BLAS", .kind = Kind::advanced, .description = "Rays find occupied bricks instead of whole volumes"} + ); + int64_t voxels_blas_budget = param( + &voxels_blas_budget, "voxels.blas_budget", 262144, + {.name = "BLAS bricks per frame", + .min = 4096, + .max = 4194304, + .unit = "bricks", + .kind = Kind::advanced, + .description = "Bricks of acceleration structure built per frame"} + ); + double voxels_trace_cell_size = param( + &voxels_trace_cell_size, "voxels.trace_cell_size", 4.0, + {.name = "Trace grid cell", + .min = 0.5, + .max = 32.0, + .unit = "m", + .kind = Kind::advanced, + .description = "Cell size of the grid marched rays walk"} + ); + int64_t voxels_shadow_instances = param( + &voxels_shadow_instances, "voxels.shadow_instances", 256, + {.name = "Shadow ray instances", + .min = 1, + .max = 4096, + .kind = Kind::advanced, + .description = "Nearest volumes a marched shadow ray tests"} + ); + bool voxels_cell_boxes = param( + &voxels_cell_boxes, "voxels.cell_boxes", true, + {.name = "Cell boxes", .kind = Kind::advanced, .description = "Draw a box per occupied cell instead of one per volume"} + ); + bool voxels_occlusion = param( + &voxels_occlusion, "voxels.occlusion", true, + {.name = "Occlusion culling", + .kind = Kind::advanced, + .description = "Skip cells hidden behind closer geometry. Needs cell boxes"} + ); + bool voxels_mesh_shaders = param( + &voxels_mesh_shaders, "voxels.mesh_shaders", true, + {.name = "Mesh shaders", + .kind = Kind::advanced, + .description = "Mesh voxels near the camera with mesh shaders when the GPU has them"} + ); + double voxels_raster_pixels = param( + &voxels_raster_pixels, "voxels.raster_pixels", 4.0, + {.name = "Raster voxel size", + .min = 0.0, + .max = 32.0, + .unit = "px", + .kind = Kind::advanced, + .description = "Cells whose voxels cover this many pixels are meshed instead of marched"} + ); + double voxels_occlusion_min_hidden = param( + &voxels_occlusion_min_hidden, "voxels.occlusion_min_hidden", 0.05, + {.name = "Occlusion idle below", + .min = 0.0, + .max = 0.5, + .kind = Kind::advanced, + .description = "Share of cells occlusion must hide to stay on. 0 never pauses it"} + ); + int64_t voxels_occlusion_idle_frames = param( + &voxels_occlusion_idle_frames, "voxels.occlusion_idle_frames", 120, + {.name = "Occlusion idle frames", + .min = 0, + .max = 600, + .unit = "frames", + .kind = Kind::advanced, + .description = "Frames occlusion stays paused before it measures again"} + ); + AssetRef environment_map = param( + &environment_map, "environment.map", AssetRef {}, + {.name = "Environment map", + .description = "Equirectangular .hdr used for the sky and the lighting. None keeps the generated sky", + .asset_type = "environment_map"} + ); + double environment_sky_intensity = param( + &environment_sky_intensity, "environment.sky_intensity", 1.0, + {.name = "Sky intensity", .min = 0.0, .max = 20.0, .description = "Brightness of the generated sky"} + ); + bool volumetrics_enabled = param( + &volumetrics_enabled, "volumetrics.enabled", true, + {.name = "Volumetrics", .description = "Fog where a post process volume sets a density"} + ); + int64_t volumetrics_quality = param( + &volumetrics_quality, "volumetrics.quality", 2, + {.name = "Volumetric quality", + .description = "Steps, lights, shadows and resolution together. Custom uses the ones below", + .options = options::volumetrics_quality} + ); + int64_t volumetrics_steps = param( + &volumetrics_steps, "volumetrics.steps", 24, + {.name = "Volumetric steps", .min = 4, .max = 96, .description = "Samples along each view ray. Custom quality only"} + ); + int64_t volumetrics_lights = param( + &volumetrics_lights, "volumetrics.lights", 8, + {.name = "Volumetric lights", .min = 0, .max = 32, .description = "Local lights each step scatters. Custom quality only"} + ); + bool volumetrics_light_shadows = param( + &volumetrics_light_shadows, "volumetrics.light_shadows", true, + {.name = "Volumetric light shadows", .description = "Local lights cast shadows into the fog. Custom quality only"} + ); + int64_t volumetrics_resolution = param( + &volumetrics_resolution, "volumetrics.resolution", 0, + {.name = "Volumetric resolution", + .description = "Fog resolution. Custom quality only", + .options = options::volumetrics_resolution} + ); + double volumetrics_distance = param( + &volumetrics_distance, "volumetrics.distance", 100.0, + {.name = "Volumetric distance", .min = 10.0, .max = 1000.0, .unit = "m", .description = "How far fog volumes are visible"} + ); + bool display_debug_overlay = param( + &display_debug_overlay, "display.debug_overlay", false, + {.name = "Debug overlay in game", + .kind = Kind::debug, + .description = "Show the debug windows in the game and free the cursor. F3 toggles it"} + ); + int64_t view_mode = param( + &view_mode, "view_mode", 0, + {.name = "View mode", + .kind = Kind::debug, + .description = "What the viewport shows instead of the lit scene, in the order of its Mode menu", + .options = options::view_mode} + ); + bool editor_camera = param( + &editor_camera, "editor_camera", false, + {.name = "Editor camera", + .kind = Kind::debug, + .description = + "Look through a fly camera instead of the scene's own, in the editor or the game. WASD moves, Q and E go down and " + "up, Shift is faster, hold the right mouse button to look"} + ); + bool voxels_glass_cost_view = param( + &voxels_glass_cost_view, "voxels.glass_cost_view", false, + {.name = "Glass cost view", + .kind = Kind::debug, + .description = "Colors each pixel by what its glass cost: green bricks, red lit surfaces, blue reflections"} + ); + bool display_hdr = param( + &display_hdr, "display.hdr", true, + {.name = "HDR output", .description = "Show HDR when the display has it turned on in the system", .requires_restart = true} + ); + int64_t quality_ray_tracing = param( + &quality_ray_tracing, "quality.ray_tracing", 0, + {.name = "Hardware ray tracing", + .kind = Kind::advanced, + .description = "Auto uses it only on GPUs built for it. Off keeps the raster paths everywhere", + .options = options::quality_ray_tracing, + .requires_restart = true} + ); + bool voxels_trace_ray_query = param( + &voxels_trace_ray_query, "voxels.trace_ray_query", true, + {.name = "Ray query voxel rays", + .kind = Kind::advanced, + .description = "Marched voxel rays use hardware ray queries when the GPU has them", + .requires_restart = true} + ); + bool gi_enabled = param( + &gi_enabled, "gi.enabled", true, + {.name = "Radiance clipmap", + .description = "World space voxel clipmap that cones gather bounce light from. Custom preset only"} + ); + int64_t gi_quality = param( + &gi_quality, "gi.quality", 2, + {.name = "Quality", + .description = "Clipmap resolution and level count together. Custom uses the ones below", + .options = options::gi_quality} + ); + double gi_intensity = param( + &gi_intensity, "gi.intensity", 2.0, + {.name = "Bounce intensity", .min = 0.0, .max = 8.0, .description = "Strength of the bounced light. 1 is physical"} + ); + double gi_clip_cell = param( + &gi_clip_cell, "gi.clip_cell", 0.2, + {.name = "Clipmap cell", + .min = 0.1, + .max = 1.0, + .unit = "m", + .description = "Metres per cell of level 0. Every level doubles it"} + ); + int64_t gi_clip_resolution = param( + &gi_clip_resolution, "gi.clip_resolution", 1, + {.name = "Clipmap resolution", + .description = "Cells per side of each level. Custom quality only", + .options = options::gi_clip_resolution} + ); + int64_t gi_clip_levels = param( + &gi_clip_levels, "gi.clip_levels", 4, + {.name = "Clipmap levels", .min = 1, .max = 6, .description = "Levels around the camera. Custom quality only"} + ); + int64_t gi_clip_debug_view = param( + &gi_clip_debug_view, "gi.clip_debug_view", 0, + {.name = "Clipmap view", + .kind = Kind::debug, + .description = "Draws one clipmap level's cells instead of the scene", + .options = options::gi_clip_debug_view} + ); + int64_t gi_clip_debug_mode = param( + &gi_clip_debug_mode, "gi.clip_debug_mode", 0, + {.name = "Clipmap view shows", + .kind = Kind::debug, + .description = "What the clipmap view draws per cell", + .options = options::gi_clip_debug_mode} + ); + int64_t video_frame_cache_mb = param( + &video_frame_cache_mb, "video.frame_cache_mb", 512, + {.name = "Video frame cache", + .min = 0, + .unit = "MB", + .description = "RAM for decoded video loops. A video that does not fit keeps decoding every frame. 0 disables the " + "cache. Applies to videos loaded after the change"} + ); +}; + +[[nodiscard]] +TOAST_API auto rendererParams() -> RendererParams&; + +} diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index 66cfc25cf..139000ee9 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -3,17 +3,18 @@ #include "toast/renderer/lighting/shadow_constants.hpp" #include "toast/renderer/lighting/shadow_slots.hpp" #include "toast/renderer/passes/lighting/environment_pass.hpp" +#include "toast/renderer/settings/renderer_params.hpp" #include "toast/renderer/shaders/shader_compiler.hpp" #include "toast/renderer/vulkan_renderer.hpp" +#include #include -#include +#include +#include namespace renderer { namespace { -using toast::settings::Meta; - constexpr uint32_t k_tiers_per_branch = 4; constexpr uint32_t k_preset_custom = 2 * k_tiers_per_branch; @@ -277,7 +278,7 @@ void applyPreset() { shadows::setPointShadowBudget(knobs.point_budget); } -using toast::settings::Value; +using toast::params::Value; struct DrivenSetting { std::string_view key; @@ -316,9 +317,9 @@ const std::array k_driven { /// Custom starts from the tier it leaves void seedSettingsFrom(const PresetKnobs& tier) { - auto& settings = toast::settings::Settings::get(); + auto& registry = toast::params::Registry::get(); for (const DrivenSetting& driven : k_driven) { - settings.setValue(driven.key, driven.get(tier), true); + registry.request(std::string {driven.key}, driven.get(tier), registry.authoringLayer()); } } @@ -338,77 +339,28 @@ constexpr auto k_to_float = [](double v) { return static_cast(v); }; constexpr auto k_to_count = [](int64_t v) { return static_cast(std::max(v, 0)); }; void registerDisplay(VulkanRenderer& renderer) { - toast::settings::declareBool( - "renderer.display.clamp_to_simulation", - true, - {.label = "Clamp to game thread", - .category = "Display", - .description = "On (default): the render thread waits for each new simulation frame instead of " - "presenting it more than once, so it never draws faster than the game thread ticks. " - "Off: the render thread never waits, repeating the last frame as fast as the GPU " - "allows (100% GPU usage) between simulation updates."} - ) - .onChange([&renderer](bool clamp) { renderer.setClampToSimulation(clamp); }); - - toast::settings::declareBool( - "renderer.display.low_latency", - true, - {.label = "Low latency", - .category = "Display", - .description = "On (default): the render thread waits for the GPU to finish the previous frame before " - "taking the next one, so input reaches the screen up to two frames sooner. Off: up to three " - "frames queue on the GPU, which can raise the frame rate a little when GPU bound."} - ) - .onChange([&renderer](bool enabled) { renderer.setLowLatency(enabled); }); - - toast::settings::declareFloat( - "renderer.display.frame_rate_limit", - 0.0, - {.label = "Frame rate limit", - .category = "Display", - .description = "Hz the render thread draws and presents at. 0 runs uncapped. Applies in either mode.", - .min = 0.0, - .max = 360.0, - .step = 1.0} - ) - .onChange([&renderer](double v) { renderer.setFrameRateLimit(v); }); + auto& p = rendererParams(); + toast::params::onChange(p.display_clamp_to_simulation, [&renderer](bool clamp) { renderer.setClampToSimulation(clamp); }); + + toast::params::onChange(p.display_low_latency, [&renderer](bool enabled) { renderer.setLowLatency(enabled); }); + + toast::params::onChange(p.display_frame_rate_limit, [&renderer](double v) { renderer.setFrameRateLimit(v); }); static float hdr_paper_white = 0.0f; static float hdr_peak = 0.0f; - toast::settings::declareFloat( - "renderer.display.hdr_paper_white", - 0.0, - {.label = "HDR paper white", - .category = "Display", - .description = "Nits that SDR white and the UI sit at when HDR output is on. 0 follows the Windows SDR content " - "brightness slider", - .min = 0.0, - .max = 500.0, - .step = 5.0} - ) - .onChange([&renderer](double v) { - hdr_paper_white = static_cast(v); - renderer.setHdrNits(hdr_paper_white, hdr_peak); - }); - - toast::settings::declareFloat( - "renderer.display.hdr_peak", - 0.0, - {.label = "HDR peak brightness", - .category = "Display", - .description = "Nits the tonemap rolls highlights off toward when HDR output is on. 0 uses what the display reports, " - "1000 when it does not say", - .min = 0.0, - .max = 4000.0, - .step = 50.0} - ) - .onChange([&renderer](double v) { - hdr_peak = static_cast(v); - renderer.setHdrNits(hdr_paper_white, hdr_peak); - }); + toast::params::onChange(p.display_hdr_paper_white, [&renderer](double v) { + hdr_paper_white = static_cast(v); + renderer.setHdrNits(hdr_paper_white, hdr_peak); + }); + + toast::params::onChange(p.display_hdr_peak, [&renderer](double v) { + hdr_peak = static_cast(v); + renderer.setHdrNits(hdr_paper_white, hdr_peak); + }); } /// Dev builds keep Custom and players start on a tier for their GPU +[[maybe_unused]] auto defaultPreset(VulkanRenderer& renderer) -> int64_t { #if defined(TOAST_DEV_TOOLS) static_cast(renderer); @@ -423,1024 +375,345 @@ auto defaultPreset(VulkanRenderer& renderer) -> int64_t { } void registerQuality(VulkanRenderer& renderer) { - toast::settings::declareInt( - "renderer.quality.preset", - defaultPreset(renderer), - { - .label = "Preset", - .category = "Quality", - .description = "Reflections, AO, shadows, voxel lighting, volumetrics, GI and render scale together. The RT tiers need " - "hardware ray tracing and run the matching non RT tier without it. Custom uses each setting", - .options = {"Low", "Medium", "High", "Epic", "Low RT", "Medium RT", "High RT", "Epic RT", "Custom"} - } - ) - .onChange([](int64_t v) { - const auto next = static_cast(std::clamp(v, 0, k_preset_custom)); - std::optional seed; - { - const std::lock_guard lock(g_preset.mutex); - if (g_preset.ready && g_preset.preset < k_preset_custom && next == k_preset_custom) { - seed = activeKnobs(); - g_preset.knobs = *seed; - } - g_preset.preset = next; - } - if (seed.has_value()) { - seedSettingsFrom(*seed); - } - if (next >= k_tiers_per_branch && next < k_preset_custom && !g_preset.renderer->getCore().isRayTracingSupported()) { - TOAST_INFO("Render", "Ray tracing is not in use on this device so the RT preset runs its non RT tier"); - } - applyPreset(); - }); - - toast::settings::declareFloat( - "renderer.quality.render_scale", - 1.0, - {.label = "Render scale", - .category = "Quality", - .description = - "Share of the output resolution the world renders at before TAA upsamples it. Presets cap it at 0.67 (DLSS Quality) " - "on a laptop GPU with DLSS. Preset Custom only", - .min = 0.1, - .max = 1.0, - .step = 0.05} - ) - .onChange(presetKnob(&PresetKnobs::render_scale, k_to_float)); - - const auto pass_toggle = [&renderer](std::string_view key, std::string_view pass, bool default_value, std::string description) { - toast::settings::declareBool( - key, default_value, {.label = std::string {pass}, .category = "Quality", .description = std::move(description)} - ) - .onChange([&renderer, pass](bool enabled) { renderer.setPostProcessPassEnabled(pass, enabled); }); - }; + auto& p = rendererParams(); + toast::params::onChange(p.quality_preset, [](int64_t v) { + const auto next = static_cast(std::clamp(v, 0, k_preset_custom)); + std::optional seed; + { + const std::lock_guard lock(g_preset.mutex); + if (g_preset.ready && g_preset.preset < k_preset_custom && next == k_preset_custom) { + seed = activeKnobs(); + g_preset.knobs = *seed; + } + g_preset.preset = next; + } + if (seed.has_value()) { + seedSettingsFrom(*seed); + } + if (next >= k_tiers_per_branch && next < k_preset_custom && !g_preset.renderer->getCore().isRayTracingSupported()) { + TOAST_INFO("Render", "Ray tracing is not in use on this device so the RT preset runs its non RT tier"); + } + applyPreset(); + }); - pass_toggle("renderer.quality.bloom", "Bloom", true, "Glow around highlights bright enough to overwhelm a lens."); - pass_toggle( - "renderer.quality.lens_flare", - "Lens flare", - true, - "Ghosts, halo and glare streaks from the brightest pixels. Tuned on the post process volume." - ); - toast::settings::declareFloat( - "renderer.quality.glass_glow_scale", - 1.0, - {.label = "Emissive behind glass", - .category = "Quality", - .description = "Scale on the light behind glass that bloom and lens flares see, so emissives the glass dims " - "still glow and flare. 0 lets glass dim them like everything else, 1 sees them as if the glass " - "were not there and higher boosts them. Lit surfaces behind glass are scaled too", - .min = 0.0, - .max = 16.0, - .step = 0.1} - ) - .onChange([&renderer](double v) { renderer.setGlassGlowScale(static_cast(v)); }); - toast::settings::declareBool( - "renderer.quality.ssr", - true, - {.label = "SSR", .category = "Quality", .description = "Screen-space reflections. Preset Custom only"} - ) - .onChange(presetKnob(&PresetKnobs::ssr, k_same_bool)); - toast::settings::declareBool( - "renderer.quality.ssao", - true, - {.label = "SSAO", - .category = "Quality", - .description = "Contact darkening where geometry meets geometry. Preset Custom only"} - ) - .onChange(presetKnob(&PresetKnobs::ssao, k_same_bool)); - - toast::settings::declareBool( - "renderer.quality.motion_blur", - false, - {.label = "Motion blur", - .category = "Quality", - .description = "Blurs the image along the motion vectors of the frame. Preset Custom only"} - ) - .onChange(presetKnob(&PresetKnobs::motion_blur, k_same_bool)); - - toast::settings::declareFloat( - "renderer.quality.motion_blur_strength", - 0.5, - {.label = "Motion blur shutter", - .category = "Quality", - .description = "Share of the frame the shutter stays open. 0.5 is a 180 degree shutter", - .min = 0.0, - .max = 1.0, - .step = 0.05} - ) - .onChange([&renderer](double v) { renderer.setMotionBlurStrength(static_cast(v)); }); - - toast::settings::declareFloat( - "renderer.quality.motion_blur_max_length", - 0.04, - {.label = "Motion blur max length", - .category = "Quality", - .description = "Longest blur as a share of the screen height", - .min = 0.005, - .max = 0.2, - .step = 0.005} - ) - .onChange([&renderer](double v) { renderer.setMotionBlurMaxLength(static_cast(v)); }); - - toast::settings::declareInt( - "renderer.quality.motion_blur_samples", - 12, - {.label = "Motion blur samples", - .category = "Quality", - .description = "Taps along each blur. More is smoother and costs more", - .min = 4.0, - .max = 32.0} - ) - .onChange([&renderer](int64_t v) { renderer.setMotionBlurSamples(static_cast(std::max(v, 2))); }); - - toast::settings::declareFloat( - "renderer.quality.ssr_reach", - 0.0, - {.label = "SSR reach", - .category = "Quality", - .description = "Most meters an SSR ray travels before the screen edge stops it, with the steps below in place of the " - "post process volume. Preset Custom only", - .min = 0.0, - .max = 500.0, - .step = 1.0} - ) - .onChange(presetKnob(&PresetKnobs::ssr_reach, k_to_float)); - - toast::settings::declareInt( - "renderer.quality.ssr_steps", - 0, - {.label = "SSR steps", - .category = "Quality", - .description = "Most depth pyramid steps an SSR ray takes. 0 keeps the post process volume values. Preset Custom only", - .min = 0.0, - .max = 256.0} - ) - .onChange(presetKnob(&PresetKnobs::ssr_steps, k_to_count)); - pass_toggle("renderer.quality.fxaa", "FXAA", true, "Edge anti-aliasing on the tonemapped image. Skipped while TAA is on."); - - toast::settings::declareBool( - "renderer.quality.taa", - true, - {.label = "TAA", - .category = "Quality", - .description = "Temporal anti-aliasing. Jitters the camera and resolves across frames in place of FXAA."} - ) - .onChange([&renderer](bool enabled) { renderer.setTaaEnabled(enabled); }); - - toast::settings::declareInt( - "renderer.quality.antialiasing", - 1, - { - .label = "Anti-aliasing", - .category = "Quality", - .description = "DLSS on NVIDIA RTX GPUs, TAA everywhere else. Needs TAA on.", - .options = {"TAA", "DLSS"} +#if !defined(TOAST_DEV_TOOLS) + if (!toast::params::of(p.quality_preset).layerValue(toast::params::Layer::project) && + !toast::params::of(p.quality_preset).layerValue(toast::params::Layer::saved)) { + toast::params::of(p.quality_preset) + .setLayer(toast::params::Layer::project, Value {toast::params::Scalar {defaultPreset(renderer)}}); } - ) - .onChange([&renderer](int64_t mode) { renderer.setDlssRequested(mode == 1); }); - - toast::settings::declareFloat( - "renderer.quality.taa_history", - 0.9, - {.label = "TAA history", - .category = "Quality", - .description = "Share of the previous frame each pixel keeps. Higher is smoother and ghosts more.", - .min = 0.5, - .max = 0.98, - .step = 0.01} - ) - .onChange([&renderer](double v) { renderer.setTaaHistoryWeight(static_cast(v)); }); - - toast::settings::declareBool( - "renderer.quality.traced_shadows", - false, - {.label = "Traced shadows", - .category = "Quality", - .description = "Trace shadow rays against the acceleration structure instead of sampling the shadow " - "maps. No effect on a device without ray query."} - ) - .onChange([&renderer](bool enabled) { renderer.setTracedShadowsEnabled(enabled); }); +#endif + + toast::params::onChange(p.quality_render_scale, presetKnob(&PresetKnobs::render_scale, k_to_float)); + + toast::params::onChange(p.quality_bloom, [&renderer](bool enabled) { renderer.setPostProcessPassEnabled("Bloom", enabled); }); + toast::params::onChange(p.quality_lens_flare, [&renderer](bool enabled) { + renderer.setPostProcessPassEnabled("Lens flare", enabled); + }); + toast::params::onChange(p.quality_glass_glow_scale, [&renderer](double v) { + renderer.setGlassGlowScale(static_cast(v)); + }); + toast::params::onChange(p.quality_ssr, presetKnob(&PresetKnobs::ssr, k_same_bool)); + toast::params::onChange(p.quality_ssao, presetKnob(&PresetKnobs::ssao, k_same_bool)); + + toast::params::onChange(p.quality_motion_blur, presetKnob(&PresetKnobs::motion_blur, k_same_bool)); + + toast::params::onChange(p.quality_motion_blur_strength, [&renderer](double v) { + renderer.setMotionBlurStrength(static_cast(v)); + }); + + toast::params::onChange(p.quality_motion_blur_max_length, [&renderer](double v) { + renderer.setMotionBlurMaxLength(static_cast(v)); + }); + + toast::params::onChange(p.quality_motion_blur_samples, [&renderer](int64_t v) { + renderer.setMotionBlurSamples(static_cast(std::max(v, 2))); + }); + + toast::params::onChange(p.quality_ssr_reach, presetKnob(&PresetKnobs::ssr_reach, k_to_float)); + + toast::params::onChange(p.quality_ssr_steps, presetKnob(&PresetKnobs::ssr_steps, k_to_count)); + toast::params::onChange(p.quality_fxaa, [&renderer](bool enabled) { renderer.setPostProcessPassEnabled("FXAA", enabled); }); + + toast::params::onChange(p.quality_taa, [&renderer](bool enabled) { renderer.setTaaEnabled(enabled); }); + + toast::params::onChange(p.quality_antialiasing, [&renderer](int64_t mode) { renderer.setDlssRequested(mode == 1); }); + + toast::params::onChange(p.quality_taa_history, [&renderer](double v) { renderer.setTaaHistoryWeight(static_cast(v)); }); + + toast::params::onChange(p.quality_traced_shadows, [&renderer](bool enabled) { renderer.setTracedShadowsEnabled(enabled); }); } void registerShadows() { + auto& p = rendererParams(); const auto resolutions = std::vector {"256", "512", "1024", "2048", "4096"}; - toast::settings::declareInt( - "renderer.shadows.cascade_resolution", - 2, - {.label = "Cascade resolution", - .category = "Shadows", - .description = "Per-cascade square resolution for directional shadows.", - .options = resolutions, - .requires_restart = true} - ) - .onChange([resolutions](int64_t index) { - if (index >= 0 && std::cmp_less(index, resolutions.size())) { - shadows::setCascadeResolution(static_cast(std::stoul(resolutions[index]))); - } - }); - - toast::settings::declareInt( - "renderer.shadows.punctual_resolution", - 1, - {.label = "Punctual resolution", - .category = "Shadows", - .description = "Full-size layer resolution for spot and point light shadows.", - .options = resolutions, - .requires_restart = true} - ) - .onChange([resolutions](int64_t index) { - if (index >= 0 && std::cmp_less(index, resolutions.size())) { - shadows::setPunctualResolution(static_cast(std::stoul(resolutions[index]))); - } - }); - - toast::settings::declareFloat( - "renderer.shadows.distance", - shadows::k_shadow_distance, - {.label = "Shadow distance", - .category = "Shadows", - .description = "How far from the camera directional shadows are fitted, in " - "metres. The cascades cover this range, so lowering it buys " - "sharpness rather than performance.", - .min = 10.0, - .max = 1000.0, - .step = 5.0} - ) - .onChange(presetKnob(&PresetKnobs::shadow_distance, k_to_float)); - - toast::settings::declareFloat( - "renderer.shadows.slot_retention", - shadow_slots::k_default_retention, - {.label = "Slot retention", - .category = "Shadows", - .description = "How many times more important than the weakest shadowed light another light must be to " - "take its shadow slot. Higher keeps cached shadow maps longer.", - .min = 1.0, - .max = 4.0, - .step = 0.05} - ) - .onChange([](double v) { shadow_slots::setRetention(static_cast(v)); }); - - toast::settings::declareInt( - "renderer.shadows.slot_grace", - shadow_slots::k_default_grace_frames, - {.label = "Slot grace", - .category = "Shadows", - .description = "Frames a shadowed light keeps its slot after leaving the view while another light wants " - "it. Higher re-renders less when looking around, lower favours what is on screen.", - .min = 0.0, - .max = 300.0, - .step = 1.0} - ) - .onChange([](int64_t frames) { shadow_slots::setGraceFrames(static_cast(std::max(frames, 0))); }); - - toast::settings::declareInt( - "renderer.shadows.spot_slots", - shadows::k_default_spot_shadows, - {.label = "Spot shadow slots", - .category = "Shadows", - .description = "Spot lights that can hold a shadow. Each slot is one punctual layer in every copy of the map, " - "about 3 MB at 512", - .min = 0.0, - .max = static_cast(shadows::k_max_spot_shadows), - .step = 1.0, - .requires_restart = true} - ) - .onChange([](int64_t slots) { shadows::setSpotShadowSlots(static_cast(std::max(slots, 0))); }); - - toast::settings::declareInt( - "renderer.shadows.point_slots", - shadows::k_default_point_shadows, - {.label = "Point shadow slots", - .category = "Shadows", - .description = "Point lights that can hold a shadow. Each slot is six punctual layers in every copy of the map, " - "about 18 MB at 512", - .min = 0.0, - .max = static_cast(shadows::k_max_point_shadows), - .step = 1.0, - .requires_restart = true} - ) - .onChange([](int64_t slots) { shadows::setPointShadowSlots(static_cast(std::max(slots, 0))); }); - - toast::settings::declareInt( - "renderer.shadows.spot_budget", - shadows::k_max_spot_shadows, - {.label = "Spot lights casting", - .category = "Shadows", - .description = "Of the spot shadow slots how many may be used at once, nearest lights first. Lowers live " - "without a restart to compare costs", - .min = 0.0, - .max = static_cast(shadows::k_max_spot_shadows), - .step = 1.0} - ) - .onChange(presetKnob(&PresetKnobs::spot_budget, k_to_count)); - - toast::settings::declareInt( - "renderer.shadows.point_budget", - shadows::k_max_point_shadows, - {.label = "Point lights casting", - .category = "Shadows", - .description = "Of the point shadow slots how many may be used at once, nearest lights first. Each costs six " - "shadow faces whenever its casters change", - .min = 0.0, - .max = static_cast(shadows::k_max_point_shadows), - .step = 1.0} - ) - .onChange(presetKnob(&PresetKnobs::point_budget, k_to_count)); - - toast::settings::declareFloat( - "renderer.shadows.full_resolution_ranges", - shadows::k_punctual_full_resolution_ranges, - {.label = "Full resolution reach", - .category = "Shadows", - .description = "Camera distance in light ranges within which a spot or point shadow keeps its full " - "resolution. Past it each doubling of the distance halves the shadow map", - .min = 0.5, - .max = 16.0, - .step = 0.5} - ) - .onChange([](double ranges) { shadows::setPunctualFullResolutionRanges(static_cast(ranges)); }); - - toast::settings::declareFloat( - "renderer.shadows.cascade_split_lambda", - shadows::k_cascade_split_lambda, - {.label = "Cascade split", - .category = "Shadows", - .description = "0 spaces the cascades evenly and 1 logarithmically. Higher keeps more resolution near the " - "camera", - .min = 0.0, - .max = 1.0, - .step = 0.05} - ) - .onChange([](double lambda) { shadows::setCascadeSplitLambda(static_cast(lambda)); }); - - toast::settings::declareFloat( - "renderer.shadows.cascade_padding", - shadows::k_cascade_padding, - {.label = "Cascade padding", - .category = "Shadows", - .description = "Extra share of its slice each cascade covers so it keeps its cached shadow map while the " - "camera moves inside it. Higher re-renders less and blurs a little more", - .min = 0.0, - .max = 0.5, - .step = 0.01} - ) - .onChange([](double padding) { shadows::setCascadePadding(static_cast(padding)); }); - - toast::settings::declareFloat( - "renderer.shadows.cascade_receiver_depth", - shadows::k_cascade_receiver_depth_radii, - {.label = "Cascade receiver depth", - .category = "Shadows", - .description = "How far along the light each cascade reaches in cascade radii. Lower draws fewer casters " - "and loses shadows on surfaces far down the light", - .min = 1.0, - .max = 16.0, - .step = 0.5} - ) - .onChange([](double radii) { shadows::setCascadeReceiverDepthRadii(static_cast(radii)); }); - - toast::settings::declareBool( - "renderer.shadows.static_cache", - true, - {.label = "Static caster cache", - .category = "Shadows", - .description = "Resting voxel volumes render into a cached map that each shadow copies under the moving " - "casters. Off draws every voxel caster whenever anything in that shadow changes"} - ) - .onChange([](bool enabled) { shadows::setStaticCasterCache(enabled); }); - - toast::settings::declareFloat( - "renderer.shadows.caster_tolerance", - shadows::k_caster_tolerance, - {.label = "Caster tolerance", - .category = "Shadows", - .description = "Meters a voxel volume may drift before its shadow follows. Higher keeps jittering bodies " - "in the static cache, lower makes slow shadows step less", - .min = 0.0, - .max = 0.1, - .step = 0.005} - ) - .onChange([](double meters) { shadows::setCasterTolerance(static_cast(meters)); }); - - toast::settings::declareBool( - "renderer.shadows.voxel_mesh_shaders", - true, - {.label = "Mesh shader voxel casters", - .category = "Shadows", - .description = "Voxel casters rasterize task and mesh shader quads on GPUs that have them. Off marches " - "every voxel caster per shadow texel"} - ) - .onChange([](bool enabled) { shadows::setVoxelMeshShadows(enabled); }); + toast::params::onChange(p.shadows_cascade_resolution, [resolutions](int64_t index) { + if (index >= 0 && std::cmp_less(index, resolutions.size())) { + shadows::setCascadeResolution(static_cast(std::stoul(resolutions[index]))); + } + }); + + toast::params::onChange(p.shadows_punctual_resolution, [resolutions](int64_t index) { + if (index >= 0 && std::cmp_less(index, resolutions.size())) { + shadows::setPunctualResolution(static_cast(std::stoul(resolutions[index]))); + } + }); + + toast::params::onChange(p.shadows_distance, presetKnob(&PresetKnobs::shadow_distance, k_to_float)); + + toast::params::onChange(p.shadows_slot_retention, [](double v) { shadow_slots::setRetention(static_cast(v)); }); + + toast::params::onChange(p.shadows_slot_grace, [](int64_t frames) { + shadow_slots::setGraceFrames(static_cast(std::max(frames, 0))); + }); + + toast::params::onChange(p.shadows_spot_slots, [](int64_t slots) { + shadows::setSpotShadowSlots(static_cast(std::max(slots, 0))); + }); + + toast::params::onChange(p.shadows_point_slots, [](int64_t slots) { + shadows::setPointShadowSlots(static_cast(std::max(slots, 0))); + }); + + toast::params::onChange(p.shadows_spot_budget, presetKnob(&PresetKnobs::spot_budget, k_to_count)); + + toast::params::onChange(p.shadows_point_budget, presetKnob(&PresetKnobs::point_budget, k_to_count)); + + toast::params::onChange(p.shadows_full_resolution_ranges, [](double ranges) { + shadows::setPunctualFullResolutionRanges(static_cast(ranges)); + }); + + toast::params::onChange(p.shadows_cascade_split_lambda, [](double lambda) { + shadows::setCascadeSplitLambda(static_cast(lambda)); + }); + + toast::params::onChange(p.shadows_cascade_padding, [](double padding) { + shadows::setCascadePadding(static_cast(padding)); + }); + + toast::params::onChange(p.shadows_cascade_receiver_depth, [](double radii) { + shadows::setCascadeReceiverDepthRadii(static_cast(radii)); + }); + + toast::params::onChange(p.shadows_static_cache, [](bool enabled) { shadows::setStaticCasterCache(enabled); }); + + toast::params::onChange(p.shadows_caster_tolerance, [](double meters) { + shadows::setCasterTolerance(static_cast(meters)); + }); + + toast::params::onChange(p.shadows_voxel_mesh_shaders, [](bool enabled) { shadows::setVoxelMeshShadows(enabled); }); } void registerVoxels(VulkanRenderer& renderer) { - toast::settings::declareInt( - "renderer.voxels.light_candidates", - 8, - {.label = "Light candidates", - .category = "Voxels", - .description = "Lights in Sampled voxel shadow mode share one marched ray per pixel chosen among this many " - "candidates from the froxel. More is less noise and more shading work", - .min = 1.0, - .max = 32.0} - ) - .onChange(presetKnob(&PresetKnobs::light_candidates, [](int64_t v) { - return static_cast(std::max(v, 1)); - })); - - toast::settings::declareBool( - "renderer.voxels.shadow_maps_only", - false, - {.label = "Shadow maps only", - .category = "Voxels", - .description = "Every light shadows voxels with its shadow map whatever its Voxel Shadows mode says. Marched and " - "Sampled shadows trace scene rays, through ray queries when the GPU traces and else by walking the " - "software cell grid. Preset Custom only"} - ) - .onChange(presetKnob(&PresetKnobs::shadow_maps_only, k_same_bool)); - - toast::settings::declareBool( - "renderer.voxels.ambient_rays", - true, - {.label = "Ambient rays", - .category = "Voxels", - .description = "Two super-sparse rays per voxel pixel occlude ambient light by how far they get, in place of " - "SSAO. Off keeps SSAO on voxels"} - ) - .onChange(presetKnob(&PresetKnobs::ambient_rays, k_same_bool)); - - toast::settings::declareBool( - "renderer.voxels.ambient_ray_query", - true, - {.label = "Ray query ambient rays", - .category = "Voxels", - .description = "Ambient rays take the exact first hit through hardware ray queries when the GPU has them. Off " - "samples each volume eight times and can step over thin walls"} - ) - .onChange([&renderer](bool enabled) { renderer.setVoxelAmbientRayQuery(enabled); }); - - toast::settings::declareFloat( - "renderer.voxels.ambient_reach", - 2.4, - {.label = "Ambient reach", - .category = "Voxels", - .description = "Meters an ambient ray travels before it counts as open sky. Teardown clamps at 24 voxels", - .min = 0.2, - .max = 20.0, - .step = 0.1} - ) - .onChange([&renderer](double v) { renderer.setVoxelAmbientReach(static_cast(v)); }); - - toast::settings::declareBool( - "renderer.voxels.traced_specular", - true, - {.label = "Traced specular", - .category = "Voxels", - .description = "One GGX ray per reflective voxel pixel at half resolution in place of the environment and " - "SSR. Off keeps both"} - ) - .onChange(presetKnob(&PresetKnobs::traced_specular, k_same_bool)); - - toast::settings::declareFloat( - "renderer.voxels.specular_roughness", - 0.6, - {.label = "Traced specular roughness", - .category = "Voxels", - .description = "Rougher voxels keep the environment specular", - .min = 0.0, - .max = 1.0, - .step = 0.05} - ) - .onChange(presetKnob(&PresetKnobs::specular_roughness, k_to_float)); - - toast::settings::declareFloat( - "renderer.voxels.specular_reach", - 32.0, - {.label = "Traced specular reach", - .category = "Voxels", - .description = "Meters a reflection ray travels before it reads the environment. Teardown uses 32", - .min = 1.0, - .max = 200.0, - .step = 1.0} - ) - .onChange(presetKnob(&PresetKnobs::specular_reach, k_to_float)); - - toast::settings::declareBool( - "renderer.voxels.specular_hit_lights", - true, - {.label = "Traced specular hit lights", - .category = "Voxels", - .description = "Reflection rays that hit off screen take a local light and its shadow ray on top of the sun and GI. " - "Preset Custom only"} - ) - .onChange(presetKnob(&PresetKnobs::specular_hit_lights, k_same_bool)); - - toast::settings::declareInt( - "renderer.voxels.glass_lit_surfaces", - 4, - {.label = "Glass lit surfaces", - .category = "Voxels", - .description = "Glass surfaces per brick and pixel that get full lighting and reflections. Layers past it " - "only tint what is behind them", - .min = 1.0, - .max = 4.0} - ) - .onChange(presetKnob(&PresetKnobs::glass_lit_surfaces, [](int64_t v) { + auto& p = rendererParams(); + toast::params::onChange(p.voxels_light_candidates, presetKnob(&PresetKnobs::light_candidates, [](int64_t v) { + return static_cast(std::max(v, 1)); + })); + + toast::params::onChange(p.voxels_shadow_maps_only, presetKnob(&PresetKnobs::shadow_maps_only, k_same_bool)); + + toast::params::onChange(p.voxels_ambient_rays, presetKnob(&PresetKnobs::ambient_rays, k_same_bool)); + + toast::params::onChange(p.voxels_ambient_ray_query, [&renderer](bool enabled) { renderer.setVoxelAmbientRayQuery(enabled); }); + + toast::params::onChange(p.voxels_ambient_reach, [&renderer](double v) { + renderer.setVoxelAmbientReach(static_cast(v)); + }); + + toast::params::onChange(p.voxels_traced_specular, presetKnob(&PresetKnobs::traced_specular, k_same_bool)); + + toast::params::onChange(p.voxels_specular_roughness, presetKnob(&PresetKnobs::specular_roughness, k_to_float)); + + toast::params::onChange(p.voxels_specular_reach, presetKnob(&PresetKnobs::specular_reach, k_to_float)); + + toast::params::onChange(p.voxels_specular_hit_lights, presetKnob(&PresetKnobs::specular_hit_lights, k_same_bool)); + + toast::params::onChange( + p.voxels_glass_lit_surfaces, presetKnob(&PresetKnobs::glass_lit_surfaces, [](int64_t v) { return static_cast(std::clamp(v, 1, 4)); - })); - - toast::settings::declareFloat( - "renderer.voxels.glass_reflection_reach", - 32.0, - {.label = "Glass reflection reach", - .category = "Voxels", - .description = "Meters the SSR or traced reflection of the front glass layer reaches. Shorter is cheaper and " - "misses fall back to the environment", - .min = 0.0, - .max = 128.0} - ) - .onChange(presetKnob(&PresetKnobs::glass_reflection_reach, k_to_float)); - - toast::settings::declareFloat( - "renderer.voxels.glass_coarse_distance", - 30.0, - {.label = "Glass coarse shading distance", - .category = "Voxels", - .description = "Meters past which glass shades one lighting sample per 2x2 pixels on GPUs with variable rate " - "shading. 0 shades every pixel", - .min = 0.0, - .max = 500.0, - .step = 1.0} - ) - .onChange([&renderer](double v) { renderer.setVoxelGlassCoarseDistance(static_cast(v)); }); - - toast::settings::declareBool( - "renderer.voxels.glass_shadows", - true, - {.label = "Glass shadows", - .category = "Voxels", - .description = "Glass tints the light that reaches voxels behind it in every light mode. Off makes glass cast " - "no shadow and lets marched shadow rays take coarse steps through it"} - ) - .onChange(presetKnob(&PresetKnobs::glass_shadows, k_same_bool)); - - toast::settings::declareInt( - "renderer.voxels.glass_shadow_reach", - 50, - {.label = "Glass shadow reach", - .category = "Voxels", - .description = "Meters a sun looks for glass between a voxel and the sky when its shadow comes from the " - "shadow map", - .min = 1.0, - .max = 2000.0} - ) - .onChange([&renderer](int64_t v) { renderer.setVoxelGlassShadowReach(static_cast(std::max(v, 1))); }); - - toast::settings::declareInt( - "renderer.voxels.sun_reach", - 200, - {.label = "Sun ray reach", - .category = "Voxels", - .description = "Meters a marched sun shadow ray travels through voxels. Longer finds distant occluders and " - "costs more on open ground", - .min = 10.0, - .max = 2000.0} - ) - .onChange([&renderer](int64_t v) { renderer.setVoxelSunReach(static_cast(std::max(v, 1))); }); - - toast::settings::declareString( - "renderer.voxels.detail_texture", - "", - {.label = "Voxel detail texture", - .category = "Voxels", - .description = "The DetailTexture the engine packs into the texture array that palette detail ids read. " - "None keeps the neutral default", - .asset_type = "detail_texture"} - ) - .onChange([&renderer](const std::string& v) { - if (v.empty()) { - renderer.setVoxelDetailTexture({}); - } else if (v.contains("://")) { - renderer.setVoxelDetailTexture(assets::load(v)); - } else { - renderer.setVoxelDetailTexture(assets::load(toast::UID(toast::UID::fromString(v)))); - } - }); - - toast::settings::declareBool( - "renderer.voxels.trace_bricks", - true, - {.label = "Brick BLAS", - .category = "Voxels", - .description = "Ray queries find the occupied bricks a ray crosses instead of whole volumes. Off marches every " - "volume a ray crosses from end to end"} - ) - .onChange([&renderer](bool enabled) { renderer.setVoxelTraceBricks(enabled); }); - - toast::settings::declareInt( - "renderer.voxels.blas_budget", - 262144, - {.label = "BLAS bricks per frame", - .category = "Voxels", - .description = "Bricks of brick BLAS builds a frame may record. A volume waiting for its build traces as a whole", - .min = 4096.0, - .max = 4194304.0} - ) - .onChange([&renderer](int64_t v) { - renderer.setVoxelBlasBudget(static_cast(std::clamp(v, 4096, 4194304))); - }); - - toast::settings::declareFloat( - "renderer.voxels.trace_cell_size", - 4.0, - {.label = "Trace grid cell", - .category = "Voxels", - .description = "Meters per cell of the camera centred grid marched voxel rays walk without ray queries. The grid " - "is 32 cells across", - .min = 0.5, - .max = 32.0, - .step = 0.5} - ) - .onChange([&renderer](double v) { renderer.setVoxelTraceCellSize(static_cast(v)); }); - - toast::settings::declareInt( - "renderer.voxels.shadow_instances", - 256, - {.label = "Shadow ray instances", - .category = "Voxels", - .description = "Nearest drawn voxel volumes a marched shadow ray tests against. Farther volumes cast no " - "marched shadow", - .min = 1.0, - .max = 4096.0} - ) - .onChange([&renderer](int64_t v) { renderer.setVoxelShadowInstances(static_cast(std::max(v, 1))); }); - - toast::settings::declareBool( - "renderer.voxels.cell_boxes", - true, - {.label = "Cell boxes", - .category = "Voxels", - .description = "On draws one box per non-empty 32 voxel cell front to back and marches only inside it. Off " - "draws one box per volume and marches the whole volume, kept to compare the two."} - ) - .onChange([&renderer](bool enabled) { renderer.setVoxelCellBoxes(enabled); }); - - toast::settings::declareBool( - "renderer.voxels.occlusion", - true, - {.label = "Occlusion culling", - .category = "Voxels", - .description = "Skips cells hidden behind closer geometry using a depth pyramid. Needs cell boxes"} - ) - .onChange([&renderer](bool enabled) { renderer.setVoxelOcclusion(enabled); }); - - toast::settings::declareBool( - "renderer.voxels.mesh_shaders", - true, - {.label = "Mesh shaders", - .category = "Voxels", - .description = "Meshes near voxels in task and mesh shaders on GPUs that have them. Off uses the compute mesher, " - "which every GPU runs"} - ) - .onChange([&renderer](bool enabled) { renderer.setVoxelMeshShaders(enabled); }); - - toast::settings::declareFloat( - "renderer.voxels.raster_pixels", - 4.0, - {.label = "Raster voxel size", - .category = "Voxels", - .description = "Cells whose voxels cover at least this many pixels are meshed into quads and rasterized", - .min = 0.0, - .max = 32.0, - .step = 0.5} - ) - .onChange([&renderer](double pixels) { renderer.setVoxelRasterPixels(static_cast(pixels)); }); - - toast::settings::declareFloat( - "renderer.voxels.occlusion_min_hidden", - 0.05, - {.label = "Occlusion idle below", - .category = "Voxels", - .description = "Share of cells occlusion culling must hide to keep running. Below it for a few frames it " - "pauses since it costs more than it saves. 0 never pauses it", - .min = 0.0, - .max = 0.5, - .step = 0.01} - ) - .onChange([&renderer](double share) { renderer.setVoxelOcclusionMinHidden(static_cast(share)); }); - - toast::settings::declareInt( - "renderer.voxels.occlusion_idle_frames", - 120, - {.label = "Occlusion idle frames", - .category = "Voxels", - .description = "Frames occlusion culling stays paused before it measures again", - .min = 0.0, - .max = 600.0, - .step = 1.0} - ) - .onChange([&renderer](int64_t frames) { - renderer.setVoxelOcclusionIdleFrames(static_cast(std::max(frames, 0))); - }); + }) + ); + + toast::params::onChange( + p.voxels_glass_reflection_reach, presetKnob(&PresetKnobs::glass_reflection_reach, k_to_float) + ); + + toast::params::onChange(p.voxels_glass_coarse_distance, [&renderer](double v) { + renderer.setVoxelGlassCoarseDistance(static_cast(v)); + }); + + toast::params::onChange(p.voxels_glass_shadows, presetKnob(&PresetKnobs::glass_shadows, k_same_bool)); + + toast::params::onChange(p.voxels_glass_shadow_reach, [&renderer](int64_t v) { + renderer.setVoxelGlassShadowReach(static_cast(std::max(v, 1))); + }); + + toast::params::onChange(p.voxels_sun_reach, [&renderer](int64_t v) { + renderer.setVoxelSunReach(static_cast(std::max(v, 1))); + }); + + toast::params::onChange(p.voxels_detail_texture, [&renderer](const toast::params::AssetRef& asset) { + const std::string& v = asset.uri; + if (v.empty()) { + renderer.setVoxelDetailTexture({}); + } else if (v.contains("://")) { + renderer.setVoxelDetailTexture(assets::load(v)); + } else { + renderer.setVoxelDetailTexture(assets::load(toast::UID(toast::UID::fromString(v)))); + } + }); + + toast::params::onChange(p.voxels_trace_bricks, [&renderer](bool enabled) { renderer.setVoxelTraceBricks(enabled); }); + + toast::params::onChange(p.voxels_blas_budget, [&renderer](int64_t v) { + renderer.setVoxelBlasBudget(static_cast(std::clamp(v, 4096, 4194304))); + }); + + toast::params::onChange(p.voxels_trace_cell_size, [&renderer](double v) { + renderer.setVoxelTraceCellSize(static_cast(v)); + }); + + toast::params::onChange(p.voxels_shadow_instances, [&renderer](int64_t v) { + renderer.setVoxelShadowInstances(static_cast(std::max(v, 1))); + }); + + toast::params::onChange(p.voxels_cell_boxes, [&renderer](bool enabled) { renderer.setVoxelCellBoxes(enabled); }); + + toast::params::onChange(p.voxels_occlusion, [&renderer](bool enabled) { renderer.setVoxelOcclusion(enabled); }); + + toast::params::onChange(p.voxels_mesh_shaders, [&renderer](bool enabled) { renderer.setVoxelMeshShaders(enabled); }); + + toast::params::onChange(p.voxels_raster_pixels, [&renderer](double pixels) { + renderer.setVoxelRasterPixels(static_cast(pixels)); + }); + + toast::params::onChange(p.voxels_occlusion_min_hidden, [&renderer](double share) { + renderer.setVoxelOcclusionMinHidden(static_cast(share)); + }); + + toast::params::onChange(p.voxels_occlusion_idle_frames, [&renderer](int64_t frames) { + renderer.setVoxelOcclusionIdleFrames(static_cast(std::max(frames, 0))); + }); } void registerEnvironment(VulkanRenderer& renderer) { - toast::settings::declareString( - "renderer.environment.map", - "", - {.label = "Environment map", - .category = "Environment", - .description = "A Radiance .hdr equirectangular image used as the sky and image-based lighting. " - "None keeps the generated sky", - .asset_type = "environment_map"} - ) - .onChange([&renderer](const std::string& v) { - if (v.empty() || v.contains("://")) { - renderer.setGlobalEnvironmentMap(v); - } else { - renderer.setGlobalEnvironmentMap(assets::AssetManager::getURI(toast::UID(toast::UID::fromString(v)))); - } - }); - - toast::settings::declareFloat( - "renderer.environment.sky_intensity", - 1.0, - {.label = "Sky intensity", - .category = "Environment", - .description = "Brightness of the generated sky, folded into the environment maps. Changing it re-runs " - "the precompute on the next frame.", - .min = 0.0, - .max = 20.0} - ) - .onChange([&renderer](double v) { - if (auto* pass = renderer.getEnvironmentPassMutable()) { - pass->setSkyIntensity(static_cast(v)); - } - }); + auto& p = rendererParams(); + toast::params::onChange(p.environment_map, [&renderer](const toast::params::AssetRef& asset) { + const std::string& v = asset.uri; + if (v.empty() || v.contains("://")) { + renderer.setGlobalEnvironmentMap(v); + } else { + renderer.setGlobalEnvironmentMap(assets::AssetManager::getURI(toast::UID(toast::UID::fromString(v)))); + } + }); + + toast::params::onChange(p.environment_sky_intensity, [&renderer](double v) { + if (auto* pass = renderer.getEnvironmentPassMutable()) { + pass->setSkyIntensity(static_cast(v)); + } + }); } void registerVolumetrics(VulkanRenderer& renderer) { - toast::settings::declareBool( - "renderer.volumetrics.enabled", - true, - {.label = "Volumetrics", - .category = "Volumetrics", - .description = "Marched height fog where a post process volume sets a fog density. Off skips the pass"} - ) - .onChange([&renderer](bool enabled) { renderer.setVolumetrics(enabled); }); - - toast::settings::declareInt( - "renderer.volumetrics.quality", - 2, - { - .label = "Volumetric quality", - .category = "Volumetrics", - .description = "Steps, local lights, local light shadows and resolution. Custom uses the settings below", - .options = {"Low", "Medium", "High", "Epic", "Custom"} - } - ) - .onChange(presetKnob(&PresetKnobs::volumetric_quality, [](int64_t v) { - return static_cast(std::clamp(v, 0, VulkanRenderer::k_volumetric_quality_custom)); - })); - - toast::settings::declareInt( - "renderer.volumetrics.steps", - 24, - {.label = "Volumetric steps", - .category = "Volumetrics", - .description = "Samples along each view ray. Custom quality only", - .min = 4.0, - .max = 96.0} - ) - .onChange([&renderer](int64_t v) { renderer.setVolumetricSteps(static_cast(std::max(v, 1))); }); - - toast::settings::declareInt( - "renderer.volumetrics.lights", - 8, - {.label = "Volumetric lights", - .category = "Volumetrics", - .description = "Local lights of a froxel each step scatters. Custom quality only", - .min = 0.0, - .max = 32.0} - ) - .onChange([&renderer](int64_t v) { renderer.setVolumetricLights(static_cast(std::max(v, 0))); }); - - toast::settings::declareBool( - "renderer.volumetrics.light_shadows", - true, - {.label = "Volumetric light shadows", - .category = "Volumetrics", - .description = "Local lights cast shadows into the fog. Custom quality only"} - ) - .onChange([&renderer](bool enabled) { renderer.setVolumetricLightShadows(enabled); }); - - toast::settings::declareInt( - "renderer.volumetrics.resolution", - 0, - { - .label = "Volumetric resolution", - .category = "Volumetrics", - .description = "Custom quality only", - .options = {"Half", "Quarter"} - } - ) - .onChange([&renderer](int64_t v) { renderer.setVolumetricQuarterResolution(v != 0); }); - - toast::settings::declareFloat( - "renderer.volumetrics.distance", - 100.0, - {.label = "Volumetric distance", - .category = "Volumetrics", - .description = "Meters fog volumes stay visible. Height fog keeps its own Fog Distance", - .min = 10.0, - .max = 1000.0, - .step = 5.0} - ) - .onChange([&renderer](double v) { renderer.setVolumetricDistance(static_cast(v)); }); + auto& p = rendererParams(); + toast::params::onChange(p.volumetrics_enabled, [&renderer](bool enabled) { renderer.setVolumetrics(enabled); }); + + toast::params::onChange(p.volumetrics_quality, presetKnob(&PresetKnobs::volumetric_quality, [](int64_t v) { + return static_cast(std::clamp(v, 0, VulkanRenderer::k_volumetric_quality_custom)); + })); + + toast::params::onChange(p.volumetrics_steps, [&renderer](int64_t v) { + renderer.setVolumetricSteps(static_cast(std::max(v, 1))); + }); + + toast::params::onChange(p.volumetrics_lights, [&renderer](int64_t v) { + renderer.setVolumetricLights(static_cast(std::max(v, 0))); + }); + + toast::params::onChange(p.volumetrics_light_shadows, [&renderer](bool enabled) { + renderer.setVolumetricLightShadows(enabled); + }); + + toast::params::onChange(p.volumetrics_resolution, [&renderer](int64_t v) { renderer.setVolumetricQuarterResolution(v != 0); }); + + toast::params::onChange(p.volumetrics_distance, [&renderer](double v) { + renderer.setVolumetricDistance(static_cast(v)); + }); } #if defined(TOAST_DEV_TOOLS) void registerDebug(VulkanRenderer& renderer) { - toast::settings::declareBool( - k_debug_overlay_in_game, - false, - {.label = "Debug overlay in game", - .category = "Debug", - .description = "Draws the ImGui debug windows while a game camera is live and frees the cursor to use them. " - "Off hides them in game and brings them back as they were in the editor. F3 in game flips it."} - ) - .onChange([&renderer](bool visible) { renderer.setDebugOverlayInGame(visible); }); - - toast::settings::declareBool( - "renderer.debug.glass_cost_view", - false, - {.label = "Glass cost view", - .category = "Debug", - .description = "Glass adds a colour for what each pixel cost instead of drawing itself. Green builds up per glass " - "brick drawn, red per lit glass surface and blue per reflection traced or marched"} - ) - .onChange([&renderer](bool enabled) { renderer.setGlassCostView(enabled); }); + auto& p = rendererParams(); + toast::params::onChange(p.display_debug_overlay, [&renderer](bool visible) { renderer.setDebugOverlayInGame(visible); }); + toast::params::onChange(p.view_mode, [](const int64_t& mode) { + event::send(static_cast(std::max(mode, 0))); + }); + + toast::params::onChange(p.voxels_glass_cost_view, [&renderer](bool enabled) { renderer.setGlassCostView(enabled); }); } #endif } +auto rendererParams() -> RendererParams& { + static RendererParams params; + return params; +} + +void testSetPreset(uint32_t preset) { + const std::lock_guard lock(g_preset.mutex); + g_preset.preset = preset; +} + void registerRendererStartupSettings() { + auto& p = rendererParams(); registerShadows(); - toast::settings::declareBool( - k_hdr_output, - true, - {.label = "HDR output", - .category = "Display", - .description = "Presents HDR when the display has it turned on in the operating system and SDR otherwise. Off keeps " - "SDR on every display", - .requires_restart = true} - ); + toast::params::onChange(p.quality_ray_tracing, [](int64_t v) { + constexpr std::array k_modes {RayTracingMode::automatic, RayTracingMode::on, RayTracingMode::off}; + ShaderCompiler::setRayTracingMode(k_modes[static_cast(std::clamp(v, 0, 2))]); + }); - toast::settings::declareInt( - "renderer.quality.ray_tracing", - 0, - { - .label = "Hardware ray tracing", - .category = "Quality", - .description = "Auto traces only on GPUs with RT cores since drivers emulate ray query slowly elsewhere. Off keeps the " - "raster and software paths on every GPU, which is what the non RT presets are tuned for. On forces ray " - "query wherever the driver offers it", - .options = {"Auto", "On", "Off"}, - .requires_restart = true - } - ) - .onChange([](int64_t v) { - constexpr std::array k_modes {RayTracingMode::automatic, RayTracingMode::on, RayTracingMode::off}; - ShaderCompiler::setRayTracingMode(k_modes[static_cast(std::clamp(v, 0, 2))]); - }); - - toast::settings::declareBool( - "renderer.voxels.trace_ray_query", - true, - {.label = "Ray query voxel rays", - .category = "Voxels", - .description = "Marched voxel rays find the volumes they cross through hardware ray queries when the GPU has them. " - "Off walks the software cell grid on every GPU", - .requires_restart = true} - ) - .onChange([](bool enabled) { ShaderCompiler::setTraceRayQuery(enabled); }); + toast::params::onChange(p.voxels_trace_ray_query, [](bool enabled) { ShaderCompiler::setTraceRayQuery(enabled); }); } void registerGi(VulkanRenderer& renderer) { + auto& p = rendererParams(); GiSettings& gi = renderer.giSettings(); - toast::settings::declareBool( - "renderer.gi.enabled", - true, - {.label = "Radiance clipmap", - .category = "Global illumination", - .description = "World space voxel clipmap that cones gather bounce light from. Preset Custom only"} - ) - .onChange(presetKnob(&PresetKnobs::gi_enabled, k_same_bool)); - - toast::settings::declareInt( - "renderer.gi.quality", - 2, - { - .label = "Quality", - .category = "Global illumination", - .description = "Clipmap resolution and level count. Custom uses the knobs below", - .options = {"Low", "Medium", "High", "Epic", "Custom"} - } - ) - .onChange(presetKnob(&PresetKnobs::gi_quality, [](int64_t v) { - return static_cast(std::clamp(v, 0, GiSettings::k_quality_custom)); - })); - - toast::settings::declareFloat( - "renderer.gi.intensity", - 2.0, - {.label = "Bounce intensity", - .category = "Global illumination", - .description = "Multiplies the light GI bounces onto surfaces. 1 is physically based and higher makes colour bleed " - "and bounce stand out more", - .min = 0.0, - .max = 8.0, - .step = 0.1} - ) - .onChange([&gi](double v) { gi.intensity.store(static_cast(v), std::memory_order_relaxed); }); - - toast::settings::declareFloat( - "renderer.gi.clip_cell", - 0.2, - {.label = "Clipmap cell", - .category = "Global illumination", - .description = "Meters per cell of clipmap level 0. Every level doubles it", - .min = 0.1, - .max = 1.0, - .step = 0.1} - ) - .onChange([&gi](double v) { - gi.clip_cell.store(std::clamp(static_cast(v), 0.1f, 1.0f), std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.clip_resolution", - 1, - { - .label = "Clipmap resolution", - .category = "Global illumination", - .description = "Cells per side of every clipmap level. Custom quality only", - .options = {"64", "128", "192"} - } - ) - .onChange([&gi](int64_t v) { - constexpr std::array k_resolutions {64, 128, 192}; - gi.clip_resolution.store(k_resolutions[static_cast(std::clamp(v, 0, 2))], std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.clip_levels", - 4, - {.label = "Clipmap levels", - .category = "Global illumination", - .description = "Clipmap levels around the camera. Custom quality only", - .min = 1.0, - .max = 6.0} - ) - .onChange([&gi](int64_t v) { - gi.clip_levels.store(static_cast(std::clamp(v, 1, 6)), std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.clip_debug_view", - 0, - { - .label = "Clipmap view", - .category = "Global illumination", - .description = "Draws the cells of one clipmap level in place of the scene", - .options = {"Off", "Level 0", "Level 1", "Level 2", "Level 3", "Level 4", "Level 5"} - } - ) - .onChange([&gi](int64_t v) { - gi.clip_debug_view.store(static_cast(std::clamp(v, 0, 6)), std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.clip_debug_mode", - 0, - { - .label = "Clipmap view shows", - .category = "Global illumination", - .description = "What the clipmap view draws per cell", - .options = {"Albedo", "Emission", "Opacity", "Radiance"} - } - ) - .onChange([&gi](int64_t v) { - gi.clip_debug_mode.store(static_cast(std::clamp(v, 0, 3)), std::memory_order_relaxed); - }); + toast::params::onChange(p.gi_enabled, presetKnob(&PresetKnobs::gi_enabled, k_same_bool)); + + toast::params::onChange(p.gi_quality, presetKnob(&PresetKnobs::gi_quality, [](int64_t v) { + return static_cast(std::clamp(v, 0, GiSettings::k_quality_custom)); + })); + + toast::params::onChange(p.gi_intensity, [&gi](double v) { + gi.intensity.store(static_cast(v), std::memory_order_relaxed); + }); + + toast::params::onChange(p.gi_clip_cell, [&gi](double v) { + gi.clip_cell.store(std::clamp(static_cast(v), 0.1f, 1.0f), std::memory_order_relaxed); + }); + + toast::params::onChange(p.gi_clip_resolution, [&gi](int64_t v) { + constexpr std::array k_resolutions {64, 128, 192}; + gi.clip_resolution.store(k_resolutions[static_cast(std::clamp(v, 0, 2))], std::memory_order_relaxed); + }); + + toast::params::onChange(p.gi_clip_levels, [&gi](int64_t v) { + gi.clip_levels.store(static_cast(std::clamp(v, 1, 6)), std::memory_order_relaxed); + }); + + toast::params::onChange(p.gi_clip_debug_view, [&gi](int64_t v) { + gi.clip_debug_view.store(static_cast(std::clamp(v, 0, 6)), std::memory_order_relaxed); + }); + + toast::params::onChange(p.gi_clip_debug_mode, [&gi](int64_t v) { + gi.clip_debug_mode.store(static_cast(std::clamp(v, 0, 3)), std::memory_order_relaxed); + }); } -auto presetDrivenValue(std::string_view key) -> std::optional { +auto presetDrivenValue(std::string_view key) -> std::optional { const std::lock_guard lock(g_preset.mutex); if (g_preset.preset >= k_preset_custom) { return std::nullopt; @@ -1453,17 +726,6 @@ auto presetDrivenValue(std::string_view key) -> std::optional #include #include #include -#include +#include namespace renderer { @@ -17,16 +18,16 @@ class VulkanRenderer; inline constexpr std::string_view k_hdr_output = "renderer.display.hdr"; /// F3 in game view flips it -inline constexpr std::string_view k_debug_overlay_in_game = "renderer.debug.overlay_in_game"; +inline constexpr std::string_view k_debug_overlay_in_game = "renderer.display.debug_overlay"; -/// @note Call after Settings::load() and before the passes exist TOAST_API void registerRendererStartupSettings(); /// @note Call after the post process passes exist TOAST_API void registerRendererSettings(VulkanRenderer& renderer); -/// Nothing under Custom or for a setting no tier drives [[nodiscard]] -auto presetDrivenValue(std::string_view key) -> std::optional; +TOAST_API auto presetDrivenValue(std::string_view path) -> std::optional; + +TOAST_API void testSetPreset(uint32_t preset); } diff --git a/engine/src/toast/renderer/vulkan_renderer.cpp b/engine/src/toast/renderer/vulkan_renderer.cpp index 83589ee20..ba1c48daf 100644 --- a/engine/src/toast/renderer/vulkan_renderer.cpp +++ b/engine/src/toast/renderer/vulkan_renderer.cpp @@ -36,9 +36,9 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -145,13 +145,25 @@ void VulkanRenderer::queueDebugLine(glm::vec3 a, glm::vec3 b, glm::vec4 color) { } void VulkanRenderer::setActiveCamera(toast::Camera* camera) { - m_camera = camera; + m_requested_camera = camera; + m_camera = m_camera_override != nullptr ? m_camera_override : camera; +} + +void VulkanRenderer::setCameraOverride(toast::Camera* camera) { + m_camera_override = camera; + m_camera = camera != nullptr ? camera : m_requested_camera; } void VulkanRenderer::forgetCamera(const toast::Camera* camera) { if (m_camera == camera) { m_camera = nullptr; } + if (m_requested_camera == camera) { + m_requested_camera = nullptr; + } + if (m_camera_override == camera) { + m_camera_override = nullptr; + } } auto VulkanRenderer::setPostProcessPassEnabled(std::string_view name, bool enabled) -> bool { @@ -206,9 +218,9 @@ void VulkanRenderer::setRenderScale(float scale) { } } -void VulkanRenderer::requestSettingValue(std::string key, toast::settings::Value value) { +void VulkanRenderer::requestSettingValue(std::string path, toast::params::Value value) { const std::lock_guard lock(m_setting_request_mutex); - m_setting_requests.emplace_back(std::move(key), std::move(value)); + m_setting_requests.emplace_back(std::move(path), std::move(value)); } auto VulkanRenderer::renderExtent() const -> vk::Extent2D { @@ -359,7 +371,9 @@ VulkanRenderer::VulkanRenderer(const VulkanCore& core, std::unique_ptr([this](const auto& e) { m_imgui_key_events_accum.push_back({e.key, e.action != 0}); if (e.key == SDLK_F3 && e.action == event::window_input_pressed && m_game_view.load(std::memory_order_relaxed)) { - toast::settings::Settings::get().setValue(k_debug_overlay_in_game, toast::settings::Value {!debugOverlayInGame()}); + toast::params::Registry::get().request( + std::string {k_debug_overlay_in_game}, toast::params::Value {toast::params::Scalar {!debugOverlayInGame()}} + ); } return false; }); diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 9c7dfcfa4..fe227afb5 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -54,7 +54,7 @@ #include #include #include -#include +#include #include #include #include @@ -1142,6 +1142,8 @@ class VulkanRenderer { void setActiveCamera(toast::Camera* camera); + void setCameraOverride(toast::Camera* camera); + void forgetCamera(const toast::Camera* camera); [[nodiscard]] @@ -1269,7 +1271,7 @@ class VulkanRenderer { void setRenderScale(float scale); /// Thread safe and applied at the next tick - void requestSettingValue(std::string key, toast::settings::Value value); + void requestSettingValue(std::string path, toast::params::Value value); [[nodiscard]] auto renderScale() const noexcept -> float { @@ -1728,6 +1730,8 @@ class VulkanRenderer { uint32_t m_current_frame = 0; toast::Camera* m_camera = nullptr; + toast::Camera* m_requested_camera = nullptr; + toast::Camera* m_camera_override = nullptr; GizmoState m_gizmo_state; @@ -1760,7 +1764,7 @@ class VulkanRenderer { std::atomic_bool m_dlss_active {false}; std::atomic m_render_scale {1.0f}; std::mutex m_setting_request_mutex; - std::vector> m_setting_requests; + std::vector> m_setting_requests; /// Of the current targets std::atomic m_applied_render_scale {1.0f}; std::atomic m_taa_history_weight {0.9f}; @@ -2081,6 +2085,12 @@ inline void setActiveCamera(toast::Camera* camera) { } } +inline void setCameraOverride(toast::Camera* camera) { + if (VulkanRenderer::instance != nullptr) { + VulkanRenderer::instance->setCameraOverride(camera); + } +} + inline void forgetCamera(const toast::Camera* camera) { if (VulkanRenderer::instance != nullptr) { VulkanRenderer::instance->forgetCamera(camera); diff --git a/engine/src/toast/renderer/vulkan_renderer_lights.cpp b/engine/src/toast/renderer/vulkan_renderer_lights.cpp index a804f7cbe..5168f59fb 100644 --- a/engine/src/toast/renderer/vulkan_renderer_lights.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_lights.cpp @@ -36,7 +36,6 @@ #include #include #include -#include #include #include #include diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index ebeae7c4c..7c7a88cf1 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -37,7 +37,6 @@ #include #include #include -#include #include #include #include diff --git a/engine/src/toast/renderer/vulkan_renderer_resources.cpp b/engine/src/toast/renderer/vulkan_renderer_resources.cpp index 32b88c8c6..8314e55ca 100644 --- a/engine/src/toast/renderer/vulkan_renderer_resources.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_resources.cpp @@ -37,7 +37,6 @@ #include #include #include -#include #include #include #include diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index a7134d17e..66c4b30cc 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -35,9 +35,9 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -358,13 +358,13 @@ void VulkanRenderer::tick(float time) noexcept { TOAST_PHASE(phases, "Tick: settings"); // Queued by render thread UI that holds the pass lock - std::vector> setting_requests; + std::vector> setting_requests; { const std::lock_guard lock(m_setting_request_mutex); setting_requests.swap(m_setting_requests); } for (auto& [key, value] : setting_requests) { - toast::settings::Settings::get().setValue(key, value, true); + toast::params::Registry::get().request(key, value, toast::params::Layer::runtime); } if (m_rendering_paused.load(std::memory_order_relaxed)) { diff --git a/engine/src/toast/renderer/vulkan_renderer_thread.cpp b/engine/src/toast/renderer/vulkan_renderer_thread.cpp index ba875d622..dfe478222 100644 --- a/engine/src/toast/renderer/vulkan_renderer_thread.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_thread.cpp @@ -36,7 +36,6 @@ #include #include #include -#include #include #include #include diff --git a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp index d95a089e6..f1f186996 100644 --- a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include diff --git a/engine/src/toast/scripting/lua_util.cpp b/engine/src/toast/scripting/lua_util.cpp index 1947d6fb8..f2dc0c519 100644 --- a/engine/src/toast/scripting/lua_util.cpp +++ b/engine/src/toast/scripting/lua_util.cpp @@ -1,12 +1,13 @@ #include "lua_util.hpp" +#include "scripting_params.hpp" + #include namespace scripting { namespace { -constexpr int k_max_script_depth = 48; thread_local int t_script_depth = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) auto tracebackHandler(lua_State* state) -> int { @@ -26,7 +27,7 @@ auto pcallTraceback(lua_State* state, int nargs, int nresults) noexcept -> int { return status; } -ScriptDepthGuard::ScriptDepthGuard() noexcept : m_allowed(t_script_depth < k_max_script_depth) { +ScriptDepthGuard::ScriptDepthGuard() noexcept : m_allowed(t_script_depth < scriptingParams().max_call_depth) { if (m_allowed) { ++t_script_depth; } diff --git a/engine/src/toast/scripting/script_dispatch.cpp b/engine/src/toast/scripting/script_dispatch.cpp index 599c75bc6..7e9630282 100644 --- a/engine/src/toast/scripting/script_dispatch.cpp +++ b/engine/src/toast/scripting/script_dispatch.cpp @@ -1,6 +1,7 @@ #include "script_dispatch.hpp" #include "lua_state.hpp" +#include "scripting_params.hpp" #include @@ -17,7 +18,6 @@ struct DispatchJob { constexpr size_t k_tracked_interpreters = 1024; // Fewer queued calls than this run one after the other on the thread that delivers, handing them out costs more than it saves -constexpr size_t k_min_parallel_batch = 8; // Leaked on purpose: queued jobs hold node handles and Lua references that must not be destroyed during static teardown auto& g_dispatch_mutex = *new std::mutex(); // NOLINT @@ -117,7 +117,7 @@ auto ScriptDispatch::deliver(int max_rounds) -> size_t { // stay in the order they were queued, so they apply in the order they were issued, and the interpreters do not wait // for each other. A small batch is not worth handing out std::vector jobs; - if (batch.size() >= k_min_parallel_batch && toast::ThreadPool::workerCount() > 1) { + if (batch.size() >= static_cast(scriptingParams().parallel_batch) && toast::ThreadPool::workerCount() > 1) { std::unordered_map job_of_interpreter; for (size_t index = 0; index < batch.size(); ++index) { const auto [slot, inserted] = job_of_interpreter.try_emplace(batch[index].vm_index, jobs.size()); diff --git a/engine/src/toast/scripting/scripting_params.cpp b/engine/src/toast/scripting/scripting_params.cpp new file mode 100644 index 000000000..1857fb9cd --- /dev/null +++ b/engine/src/toast/scripting/scripting_params.cpp @@ -0,0 +1,10 @@ +#include "scripting_params.hpp" + +namespace scripting { + +auto scriptingParams() -> ScriptingParams& { + static ScriptingParams instance; + return instance; +} + +} diff --git a/engine/src/toast/scripting/scripting_params.hpp b/engine/src/toast/scripting/scripting_params.hpp new file mode 100644 index 000000000..1b1238085 --- /dev/null +++ b/engine/src/toast/scripting/scripting_params.hpp @@ -0,0 +1,43 @@ +/** + * @file scripting_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief Limits and thresholds of the Lua runtime + */ + +#pragma once +#include +#include +#include + +namespace scripting { + +struct ScriptingParams : toast::params::Group<"scripting"> { + using Kind = toast::params::Kind; + + int32_t max_call_depth = param( + &max_call_depth, "calls.max_depth", 48, + {.name = "Call depth", .min = 8, .max = 256, .description = "Nested script calls allowed before one is refused"} + ); + int32_t parallel_batch = param( + ¶llel_batch, "parallel.min_batch", 8, + {.name = "Parallel batch", + .min = 1, + .max = 1024, + .kind = Kind::advanced, + .description = "Fewer script calls than this run on the calling thread"} + ); + int32_t parallel_lifecycle = param( + ¶llel_lifecycle, "parallel.min_lifecycle_scripts", 16, + {.name = "Parallel lifecycle", + .min = 1, + .max = 4096, + .kind = Kind::advanced, + .description = "Fewer scripts than this start and stop on one thread"} + ); +}; + +TOAST_API auto scriptingParams() -> ScriptingParams&; + +} diff --git a/engine/src/toast/settings/settings.cpp b/engine/src/toast/settings/settings.cpp deleted file mode 100644 index 7c0992ffc..000000000 --- a/engine/src/toast/settings/settings.cpp +++ /dev/null @@ -1,492 +0,0 @@ -#include "settings.hpp" - -#include -#include - -namespace toast::settings { -namespace { - -constexpr const char* k_sink = "Settings"; - -auto layerIndex(Layer layer) -> size_t { - return static_cast(layer) - 1; -} - -auto typeOf(const Value& value) -> Type { - if (std::holds_alternative(value)) { - return Type::boolean; - } - if (std::holds_alternative(value)) { - return Type::integer; - } - if (std::holds_alternative(value)) { - return Type::floating; - } - return Type::string; -} - -/// @brief Converts @p value to @p type, or nullopt when the two describe different things -/// -/// TOML gives back whatever the file literally contained, so a float setting written as `1` parses as an -/// integer and would otherwise be rejected on load. Numeric widening is allowed for that reason; a string -/// against a number is not, because that is a genuinely wrong file rather than a formatting accident -auto coerce(const Value& value, Type type) -> std::optional { - switch (type) { - case Type::boolean: - if (const auto* b = std::get_if(&value)) { - return Value {*b}; - } - if (const auto* i = std::get_if(&value)) { - return Value {*i != 0}; - } - return std::nullopt; - case Type::integer: - if (const auto* i = std::get_if(&value)) { - return Value {*i}; - } - if (const auto* b = std::get_if(&value)) { - return Value {static_cast(*b)}; - } - if (const auto* d = std::get_if(&value)) { - return Value {static_cast(*d)}; - } - return std::nullopt; - case Type::floating: - if (const auto* d = std::get_if(&value)) { - return Value {*d}; - } - if (const auto* i = std::get_if(&value)) { - return Value {static_cast(*i)}; - } - return std::nullopt; - case Type::string: - if (const auto* s = std::get_if(&value)) { - return Value {*s}; - } - return std::nullopt; - } - return std::nullopt; -} - -auto sameValue(const Value& a, const Value& b) -> bool { - return a == b; -} - -/// @brief Splits "renderer.shadows.resolution" into its table path and leaf key -auto splitKey(std::string_view key) -> std::pair, std::string_view> { - std::vector path; - size_t start = 0; - while (true) { - const size_t dot = key.find('.', start); - if (dot == std::string_view::npos) { - break; - } - path.emplace_back(key.substr(start, dot - start)); - start = dot + 1; - } - return {path, key.substr(start)}; -} - -/// @brief Walks @p root down @p path, reading through the nesting a key's dots describe -auto tomlLookup(const toml::table& root, std::string_view key) -> const toml::node* { - const auto [path, leaf] = splitKey(key); - const toml::table* table = &root; - for (const auto& segment : path) { - const auto* child = table->get(segment); - if (child == nullptr || !child->is_table()) { - return nullptr; - } - table = child->as_table(); - } - return table->get(leaf); -} - -void tomlInsert(toml::table& root, std::string_view key, const Value& value) { - const auto [path, leaf] = splitKey(key); - toml::table* table = &root; - for (const auto& segment : path) { - auto* child = table->get(segment); - if (child == nullptr || !child->is_table()) { - table->insert_or_assign(segment, toml::table {}); - child = table->get(segment); - } - table = child->as_table(); - } - std::visit([&](const auto& v) { table->insert_or_assign(leaf, v); }, value); -} - -/// @brief Flattens a parsed file into dotted keys, so a caller never walks the nesting itself -void flatten(const toml::table& table, const std::string& prefix, std::unordered_map& out) { - for (const auto& [key, node] : table) { - const std::string full = prefix.empty() ? std::string {key.str()} : prefix + "." + std::string {key.str()}; - if (const auto* child = node.as_table()) { - flatten(*child, full, out); - } else if (const auto* b = node.as_boolean()) { - out.insert_or_assign(full, Value {b->get()}); - } else if (const auto* i = node.as_integer()) { - out.insert_or_assign(full, Value {i->get()}); - } else if (const auto* d = node.as_floating_point()) { - out.insert_or_assign(full, Value {d->get()}); - } else if (const auto* s = node.as_string()) { - out.insert_or_assign(full, Value {s->get()}); - } - } -} - -auto defaultCategory(std::string_view key) -> std::string { - const auto dot = key.rfind('.'); - return dot == std::string_view::npos ? std::string {} : std::string {key.substr(0, dot)}; -} - -auto defaultLabel(std::string_view key) -> std::string { - const auto dot = key.rfind('.'); - return std::string {dot == std::string_view::npos ? key : key.substr(dot + 1)}; -} - -} - -auto Settings::get() -> Settings& { - static Settings instance; - return instance; -} - -auto Settings::declare(std::string_view key, Type type, Value default_value, Meta meta) -> Entry* { - std::scoped_lock lock(m_mutex); - - const std::string key_str {key}; - if (const auto it = m_by_key.find(key_str); it != m_by_key.end()) { - TOAST_WARN(k_sink, "Setting '{}' declared twice; keeping the first declaration", key_str); - return it->second; - } - - if (meta.label.empty()) { - meta.label = defaultLabel(key); - } - if (meta.category.empty()) { - meta.category = defaultCategory(key); - } - - Entry& entry = m_entries.emplace_back(); - entry.key = key_str; - entry.type = type; - entry.meta = std::move(meta); - entry.default_value = std::move(default_value); - - // Anything the files already carried for this key, held since load() could not know its type yet - for (size_t layer = 0; layer < k_layer_count; ++layer) { - const auto it = m_pending[layer].find(key_str); - if (it == m_pending[layer].end()) { - continue; - } - if (auto converted = coerce(it->second, type)) { - entry.overrides[layer] = std::move(*converted); - } else { - TOAST_WARN(k_sink, "Setting '{}' has the wrong type on disk; ignoring the stored value", key_str); - } - m_pending[layer].erase(it); - } - - resolveEntry(entry); - m_by_key.emplace(key_str, &entry); - return &entry; -} - -auto Settings::declareBool(std::string_view key, bool default_value, Meta meta) -> Entry* { - return declare(key, Type::boolean, Value {default_value}, std::move(meta)); -} - -auto Settings::declareInt(std::string_view key, int64_t default_value, Meta meta) -> Entry* { - return declare(key, Type::integer, Value {default_value}, std::move(meta)); -} - -auto Settings::declareFloat(std::string_view key, double default_value, Meta meta) -> Entry* { - return declare(key, Type::floating, Value {default_value}, std::move(meta)); -} - -auto Settings::declareString(std::string_view key, std::string default_value, Meta meta) -> Entry* { - return declare(key, Type::string, Value {std::move(default_value)}, std::move(meta)); -} - -void Settings::resolveEntry(Entry& entry) { - entry.resolved = entry.default_value; - for (const auto& override : entry.overrides) { - if (override.has_value()) { - entry.resolved = *override; - } - } -} - -auto Settings::find(std::string_view key) -> Entry* { - std::scoped_lock lock(m_mutex); - const auto it = m_by_key.find(key); - return it == m_by_key.end() ? nullptr : it->second; -} - -auto Settings::entries() -> std::vector { - std::scoped_lock lock(m_mutex); - std::vector out; - out.reserve(m_entries.size()); - for (auto& entry : m_entries) { - out.push_back(&entry); - } - return out; -} - -auto Settings::value(std::string_view key) -> std::optional { - std::scoped_lock lock(m_mutex); - const auto it = m_by_key.find(key); - if (it == m_by_key.end()) { - return std::nullopt; - } - return it->second->resolved; -} - -auto Settings::resolved(const Entry* entry) -> Value { - if (entry == nullptr) { - return Value {}; - } - std::scoped_lock lock(m_mutex); - return entry->resolved; -} - -auto Settings::setValue(std::string_view key, const Value& value, bool override_higher_layers) -> bool { - std::vector> callbacks; - Value new_value; - { - std::scoped_lock lock(m_mutex); - const auto it = m_by_key.find(key); - if (it == m_by_key.end()) { - TOAST_WARN(k_sink, "setValue on undeclared setting '{}'", key); - return false; - } - - Entry& entry = *it->second; - auto converted = coerce(value, entry.type); - if (!converted.has_value()) { - TOAST_WARN( - k_sink, "setValue on '{}' with a {} value; expected a different type", entry.key, static_cast(typeOf(value)) - ); - return false; - } - - const Value previous = entry.resolved; - entry.overrides[layerIndex(m_active_layer)] = *converted; - if (override_higher_layers) { - for (size_t i = layerIndex(m_active_layer) + 1; i < entry.overrides.size(); ++i) { - entry.overrides[i].reset(); - } - } - resolveEntry(entry); - if (sameValue(previous, entry.resolved)) { - return true; - } - - m_dirty = true; - new_value = entry.resolved; - callbacks = entry.on_change; - } - - // Outside the lock: a callback may legitimately read other settings, and holding a recursive mutex across - // arbitrary engine code is how a settings change ends up owning a lock the renderer wanted - for (const auto& callback : callbacks) { - callback(new_value); - } - return true; -} - -auto Settings::reset(std::string_view key) -> bool { - std::vector> callbacks; - Value new_value; - { - std::scoped_lock lock(m_mutex); - const auto it = m_by_key.find(key); - if (it == m_by_key.end()) { - return false; - } - - Entry& entry = *it->second; - if (!entry.overrides[layerIndex(m_active_layer)].has_value()) { - return true; - } - - const Value previous = entry.resolved; - entry.overrides[layerIndex(m_active_layer)].reset(); - resolveEntry(entry); - m_dirty = true; - if (sameValue(previous, entry.resolved)) { - return true; - } - new_value = entry.resolved; - callbacks = entry.on_change; - } - - for (const auto& callback : callbacks) { - callback(new_value); - } - return true; -} - -void Settings::resetAll() { - std::vector keys; - { - std::scoped_lock lock(m_mutex); - keys.reserve(m_entries.size()); - for (const auto& entry : m_entries) { - keys.push_back(entry.key); - } - } - for (const auto& key : keys) { - reset(key); - } -} - -void Settings::setPaths(std::filesystem::path project_file, std::filesystem::path user_file) { - std::scoped_lock lock(m_mutex); - m_project_path = std::move(project_file); - m_user_path = std::move(user_file); -} - -void Settings::setActiveLayer(Layer layer) { - std::scoped_lock lock(m_mutex); - m_active_layer = layer == Layer::code ? Layer::user : layer; -} - -auto Settings::loadFile(const std::filesystem::path& path, Layer layer) -> bool { - ZoneScoped; - if (path.empty() || !std::filesystem::exists(path)) { - return false; - } - - toml::table table; - try { - table = toml::parse_file(path.string()); - } catch (const std::exception& e) { - TOAST_ERROR(k_sink, "Failed to parse {}: {}", path.string(), e.what()); - return false; - } - - std::unordered_map flat; - flatten(table, {}, flat); - - const size_t index = layerIndex(layer); - m_pending[index].clear(); - for (auto& entry : m_entries) { - entry.overrides[index].reset(); - } - - size_t applied = 0; - for (auto& [key, value] : flat) { - const auto it = m_by_key.find(key); - if (it == m_by_key.end()) { - m_pending[index].insert_or_assign(key, value); - continue; - } - if (auto converted = coerce(value, it->second->type)) { - it->second->overrides[index] = std::move(*converted); - ++applied; - } else { - TOAST_WARN(k_sink, "Setting '{}' has the wrong type in {}; ignoring it", key, path.string()); - } - } - - for (auto& entry : m_entries) { - resolveEntry(entry); - } - - TOAST_INFO(k_sink, "Loaded {} ({} applied, {} held for undeclared keys)", path.string(), applied, m_pending[index].size()); - return true; -} - -void Settings::load() { - std::scoped_lock lock(m_mutex); - loadFile(m_project_path, Layer::project); - loadFile(m_user_path, Layer::user); - m_dirty = false; -} - -auto Settings::save() -> bool { - ZoneScoped; - std::scoped_lock lock(m_mutex); - - const auto& path = m_active_layer == Layer::project ? m_project_path : m_user_path; - if (path.empty()) { - TOAST_WARN( - k_sink, "No path configured for the {} layer; nothing saved", m_active_layer == Layer::project ? "project" : "user" - ); - return false; - } - - const size_t index = layerIndex(m_active_layer); - toml::table root; - if (m_active_layer == Layer::project && std::filesystem::exists(path)) { - try { - root = toml::parse_file(path.string()); - } catch (const std::exception& e) { - TOAST_ERROR(k_sink, "Failed to parse {} before saving: {}", path.string(), e.what()); - return false; - } - } - - for (const auto& entry : m_entries) { - if (m_active_layer == Layer::project) { - tomlInsert(root, entry.key, entry.overrides[index].value_or(entry.default_value)); - continue; - } - - if (!entry.overrides[index].has_value()) { - continue; - } - - // What the value would be with this layer's override removed. Writing only genuine differences is what - // keeps a user file to the few things a player actually changed, and lets a later patch move a default - // they never touched instead of freezing today's value into their file forever - Value underneath = entry.default_value; - for (size_t below = 0; below < index; ++below) { - if (entry.overrides[below].has_value()) { - underneath = *entry.overrides[below]; - } - } - if (sameValue(underneath, *entry.overrides[index])) { - continue; - } - tomlInsert(root, entry.key, *entry.overrides[index]); - } - - // Keys nothing declared this run are written back out rather than dropped, so a settings file is never - // pruned by a build whose systems happened not to be constructed - for (const auto& [key, value] : m_pending[index]) { - tomlInsert(root, key, value); - } - - try { - if (path.has_parent_path()) { - std::filesystem::create_directories(path.parent_path()); - } - std::ofstream out(path, std::ios::trunc); - if (!out) { - TOAST_ERROR(k_sink, "Could not open {} for writing", path.string()); - return false; - } - out << root; - out << '\n'; - } catch (const std::exception& e) { - TOAST_ERROR(k_sink, "Failed to write {}: {}", path.string(), e.what()); - return false; - } - - m_dirty = false; - TOAST_INFO(k_sink, "Saved {}", path.string()); - return true; -} - -auto Settings::saveIfDirty() -> bool { - { - std::scoped_lock lock(m_mutex); - if (!m_dirty) { - return true; - } - } - return save(); -} - -} diff --git a/engine/src/toast/settings/settings.hpp b/engine/src/toast/settings/settings.hpp deleted file mode 100644 index c82929aa7..000000000 --- a/engine/src/toast/settings/settings.hpp +++ /dev/null @@ -1,292 +0,0 @@ -/** - * @file settings.hpp - * @author dario - * @date 16/08/2026 - */ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace toast::settings { - -/// @brief Storage type of a setting; the editor picks its widget from this -enum class Type : uint8_t { - boolean, - integer, - floating, - string -}; - -/** - * @brief Where a value comes from, lowest priority first - * - * `code` is the default passed to declare() and is never written to disk. `project` is authored in the editor - * and ships with the game. `user` is what a player's own tweaks land in, so a patch that changes a project - * default still reaches players who never touched that setting - * - * A resolved value is the highest layer that has an override, so writing one layer never destroys another - */ -enum class Layer : uint8_t { - code, - project, - user -}; - -inline constexpr size_t k_layer_count = 2; ///< Writable layers; `code` lives in Entry::default_value - -using Value = std::variant; - -/** - * @brief Everything the editor needs to render a setting without knowing what it is - * - * The point of carrying this on the setting rather than in the editor: a system declares its settings next to - * the code that reads them, and the settings window picks them up with no C# change. @p category is the - * grouping header, defaulting to the key minus its last segment - */ -struct Meta { - std::string label; ///< Display name; the key's last segment when empty - std::string category; ///< Grouping header; the key minus its last segment when empty - std::string description; ///< Tooltip - double min = 0.0; ///< Slider bounds; equal min and max mean unbounded - double max = 0.0; - double step = 0.0; ///< Drag increment; the editor picks one when 0 - std::vector options; ///< Non-empty makes an integer setting a combo box indexing this - bool requires_restart = false; ///< Editor marks it; the value still applies to the next run - bool hidden = false; ///< Persisted and scriptable, but not shown - std::string asset_type; ///< Makes a string setting an asset picker of this type holding the asset UID -}; - -/// @brief One registered setting. Held by the registry; `Setting` is a handle to it -struct Entry { - std::string key; - Type type = Type::boolean; - Meta meta; - Value default_value; - std::array, k_layer_count> overrides; ///< Indexed by Layer minus one - Value resolved; - std::vector> on_change; -}; - -/** - * @brief The engine-wide settings registry - * - * Systems declare their own settings next to the code that consumes them and keep the returned handle; - * nothing central has to know the list. Values arriving from disk before their declaration are held and - * applied when it happens, so load order does not matter - the renderer declares its settings when it is - * constructed, long after the files were read - * - * @note Every accessor is mutex-guarded, because the editor sets values from its UI thread while the engine - * reads them on the main thread. Systems that need a value per frame should cache it through onChange() - * rather than calling get() in a loop - */ -class TOAST_API Settings { -public: - static auto get() -> Settings&; - - auto declareBool(std::string_view key, bool default_value, Meta meta = {}) -> Entry*; - auto declareInt(std::string_view key, int64_t default_value, Meta meta = {}) -> Entry*; - auto declareFloat(std::string_view key, double default_value, Meta meta = {}) -> Entry*; - auto declareString(std::string_view key, std::string default_value, Meta meta = {}) -> Entry*; - - /// @returns the entry for @p key, or nullptr when nothing declared it - [[nodiscard]] - auto find(std::string_view key) -> Entry*; - - /// @brief Every declared setting, in declaration order - /// - /// Stable across further declarations - entries live in a deque, so the editor may hold these across a - /// frame in which another system registers - [[nodiscard]] - auto entries() -> std::vector; - - /// @returns the resolved value of @p key, or nullopt when it was never declared - [[nodiscard]] - auto value(std::string_view key) -> std::optional; - - /// @returns @p entry's resolved value; the lookup-free path Setting::value() takes - [[nodiscard]] - auto resolved(const Entry* entry) -> Value; - - /// @brief Writes @p value into the active layer and fires the setting's change callbacks - /// - /// A value of the wrong alternative is converted when the conversion is lossless-ish (int to double, bool - /// to int) and rejected otherwise, so a caller cannot silently turn a float setting into a string - /// - /// @p override_higher_layers clears the layers above the active one in memory and leaves their files alone - auto setValue(std::string_view key, const Value& value, bool override_higher_layers = false) -> bool; - - /// @brief Drops @p key's override in the active layer, exposing whatever is underneath - auto reset(std::string_view key) -> bool; - - /// @brief reset() for every declared setting - void resetAll(); - - /// @brief Points the two writable layers at their files; neither has to exist yet - void setPaths(std::filesystem::path project_file, std::filesystem::path user_file); - - /// @brief Which layer setValue() writes to - /// - /// The editor sets `project`, so what it authors ships as the game's defaults. A packaged game leaves it - /// at `user`, so a player's tweaks land in their own file and survive a patch - void setActiveLayer(Layer layer); - - [[nodiscard]] - auto activeLayer() const -> Layer { - return m_active_layer; - } - - /// @returns the file the active layer writes to - [[nodiscard]] - auto activeFilePath() const -> const std::filesystem::path& { - return m_active_layer == Layer::project ? m_project_path : m_user_path; - } - - /// @brief Reads both writable layers from disk, replacing whatever they currently hold - /// - /// Values whose key has not been declared yet are kept aside rather than dropped, and applied by the - /// declare() that eventually names them - void load(); - - /// @brief Writes the active layer, creating parent directories as needed - /// - /// Only keys that actually differ from the layer below are written, which is what keeps a user file to - /// the handful of things that were changed - and lets a later patch move a default the player never - /// touched - auto save() -> bool; - - [[nodiscard]] - auto dirty() const -> bool { - return m_dirty; - } - - /// @brief save(), but only when something changed since the last one - auto saveIfDirty() -> bool; - -private: - auto declare(std::string_view key, Type type, Value default_value, Meta meta) -> Entry*; - void resolveEntry(Entry& entry); - auto loadFile(const std::filesystem::path& path, Layer layer) -> bool; - - /// @brief Lets the map be searched by string_view, without building a std::string to throw away - struct TransparentHash { - using is_transparent = void; - - auto operator()(std::string_view key) const -> size_t { return std::hash {}(key); } - }; - - TOAST_LOCKABLE(std::recursive_mutex, m_mutex, "Settings"); - std::deque m_entries; - std::unordered_map> m_by_key; - - /// @brief Values read from disk whose key nothing has declared yet - /// - /// A settings file outlives the code that reads it: a key may belong to a system not constructed yet, or - /// to one that no longer exists. Holding them here means the first case works and the second is harmless - /// - and save() writes them back out, so a file is never silently pruned by a run that did not touch it - std::array, k_layer_count> m_pending; - - std::filesystem::path m_project_path; - std::filesystem::path m_user_path; - Layer m_active_layer = Layer::user; - bool m_dirty = false; -}; - -/** - * @brief Typed handle to a declared setting - * - * Cheap to copy and stable for the process - entries are never removed. Reading is `value()`, writing is - * `set()`, and a write persists on the next Settings::save() - */ -template -class Setting { -public: - Setting() = default; - - explicit Setting(Entry* entry) : m_entry(entry) { } - - [[nodiscard]] - auto valid() const -> bool { - return m_entry != nullptr; - } - - [[nodiscard]] - auto value() const -> T { - if (m_entry == nullptr) { - return T {}; - } - // Reads the entry directly. Going back through value(key) hashed the key and built a std::string to - // look up the entry this handle is already holding - const Value resolved = Settings::get().resolved(m_entry); - if (const auto* typed = std::get_if(&resolved)) { - return *typed; - } - return T {}; - } - - operator T() const { // NOLINT(google-explicit-constructor) - the whole point is reading it like a T - return value(); - } - - void set(T v) { - if (m_entry != nullptr) { - Settings::get().setValue(m_entry->key, Value {std::move(v)}); - } - } - - /// @brief Runs @p callback whenever this setting changes, and once immediately with the current value - /// - /// The immediate call is what lets a system express "apply this value" once and have both the initial - /// state and every later change go through the same path - void onChange(std::function callback) { - if (m_entry == nullptr) { - return; - } - auto wrapper = [callback = std::move(callback)](const Value& v) { - if (const auto* typed = std::get_if(&v)) { - callback(*typed); - } - }; - wrapper(Value {value()}); - m_entry->on_change.emplace_back(std::move(wrapper)); - } - - [[nodiscard]] - auto entry() const -> Entry* { - return m_entry; - } - -private: - Entry* m_entry = nullptr; -}; - -/// @brief declare* wrappers returning a typed handle, which is what call sites actually want -inline auto declareBool(std::string_view key, bool default_value, Meta meta = {}) -> Setting { - return Setting {Settings::get().declareBool(key, default_value, std::move(meta))}; -} - -inline auto declareInt(std::string_view key, int64_t default_value, Meta meta = {}) -> Setting { - return Setting {Settings::get().declareInt(key, default_value, std::move(meta))}; -} - -inline auto declareFloat(std::string_view key, double default_value, Meta meta = {}) -> Setting { - return Setting {Settings::get().declareFloat(key, default_value, std::move(meta))}; -} - -inline auto declareString(std::string_view key, std::string default_value, Meta meta = {}) -> Setting { - return Setting {Settings::get().declareString(key, std::move(default_value), std::move(meta))}; -} - -} diff --git a/engine/src/toast/settings/settings_ffi.cpp b/engine/src/toast/settings/settings_ffi.cpp deleted file mode 100644 index 6cd083872..000000000 --- a/engine/src/toast/settings/settings_ffi.cpp +++ /dev/null @@ -1,159 +0,0 @@ -#include "settings.hpp" - -#include - -namespace { - -using namespace toast::settings; - -/// @brief Backing store for the string returns -/// -/// A resolved value lives in a variant the next set() may reassign, and a path is a temporary once converted -/// out of std::filesystem. Neither can be handed out by address, so both are copied here first. Thread-local -/// because the editor and the engine both cross this boundary -thread_local std::string g_string_return; - -auto entryAt(int32_t index) -> Entry* { - if (index < 0) { - return nullptr; - } - auto all = Settings::get().entries(); - return static_cast(index) < all.size() ? all[static_cast(index)] : nullptr; -} - -} - -extern "C" { - -auto toast_settings_count() noexcept -> int32_t { - return static_cast(Settings::get().entries().size()); -} - -auto toast_settings_get_desc(int32_t index, toast_setting_desc* out) noexcept -> int32_t { - const Entry* entry = entryAt(index); - if (entry == nullptr || out == nullptr) { - return 0; - } - - out->key = entry->key.c_str(); - out->label = entry->meta.label.c_str(); - out->category = entry->meta.category.c_str(); - out->description = entry->meta.description.c_str(); - out->type = static_cast(entry->type); - out->min = entry->meta.min; - out->max = entry->meta.max; - out->step = entry->meta.step; - out->option_count = static_cast(entry->meta.options.size()); - out->requires_restart = entry->meta.requires_restart ? 1 : 0; - out->hidden = entry->meta.hidden ? 1 : 0; - return 1; -} - -auto toast_settings_get_asset_type(int32_t index) noexcept -> const char* { - const Entry* entry = entryAt(index); - return entry != nullptr ? entry->meta.asset_type.c_str() : ""; -} - -auto toast_settings_get_option(int32_t index, int32_t option) noexcept -> const char* { - const Entry* entry = entryAt(index); - if (entry == nullptr || option < 0 || static_cast(option) >= entry->meta.options.size()) { - return nullptr; - } - return entry->meta.options[static_cast(option)].c_str(); -} - -auto toast_settings_get_bool(const char* key) noexcept -> int32_t { - if (key == nullptr) { - return 0; - } - const auto value = Settings::get().value(key); - if (!value.has_value()) { - return 0; - } - const auto* typed = std::get_if(&*value); - return typed != nullptr && *typed ? 1 : 0; -} - -auto toast_settings_get_int(const char* key) noexcept -> int64_t { - if (key == nullptr) { - return 0; - } - const auto value = Settings::get().value(key); - if (!value.has_value()) { - return 0; - } - const auto* typed = std::get_if(&*value); - return typed != nullptr ? *typed : 0; -} - -auto toast_settings_get_float(const char* key) noexcept -> double { - if (key == nullptr) { - return 0.0; - } - const auto value = Settings::get().value(key); - if (!value.has_value()) { - return 0.0; - } - const auto* typed = std::get_if(&*value); - return typed != nullptr ? *typed : 0.0; -} - -auto toast_settings_get_string(const char* key) noexcept -> const char* { - g_string_return.clear(); - if (key != nullptr) { - if (const auto value = Settings::get().value(key)) { - if (const auto* typed = std::get_if(&*value)) { - g_string_return = *typed; - } - } - } - return g_string_return.c_str(); -} - -void toast_settings_set_bool(const char* key, int32_t value) noexcept { - if (key != nullptr) { - Settings::get().setValue(key, Value {value != 0}); - } -} - -void toast_settings_set_int(const char* key, int64_t value) noexcept { - if (key != nullptr) { - Settings::get().setValue(key, Value {value}); - } -} - -void toast_settings_set_float(const char* key, double value) noexcept { - if (key != nullptr) { - Settings::get().setValue(key, Value {value}); - } -} - -void toast_settings_set_string(const char* key, const char* value) noexcept { - if (key != nullptr && value != nullptr) { - Settings::get().setValue(key, Value {std::string {value}}); - } -} - -void toast_settings_reset(const char* key) noexcept { - if (key != nullptr) { - Settings::get().reset(key); - } -} - -void toast_settings_reset_all() noexcept { - Settings::get().resetAll(); -} - -auto toast_settings_save() noexcept -> int32_t { - return Settings::get().save() ? 1 : 0; -} - -auto toast_settings_is_dirty() noexcept -> int32_t { - return Settings::get().dirty() ? 1 : 0; -} - -auto toast_settings_active_path() noexcept -> const char* { - g_string_return = Settings::get().activeFilePath().string(); - return g_string_return.c_str(); -} -} diff --git a/engine/src/toast/time_params.cpp b/engine/src/toast/time_params.cpp new file mode 100644 index 000000000..8212b7557 --- /dev/null +++ b/engine/src/toast/time_params.cpp @@ -0,0 +1,10 @@ +#include "time_params.hpp" + +namespace toast { + +auto timeParams() -> TimeParams& { + static TimeParams instance; + return instance; +} + +} diff --git a/engine/src/toast/time_params.hpp b/engine/src/toast/time_params.hpp new file mode 100644 index 000000000..04545351b --- /dev/null +++ b/engine/src/toast/time_params.hpp @@ -0,0 +1,34 @@ +/** + * @file time_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief How fast game time runs and the longest step + */ + +#pragma once +#include +#include + +namespace toast { + +struct TimeParams : params::Group<"time"> { + using Kind = params::Kind; + + float scale = param( + &scale, "scale", 1.0F, + {.name = "Time scale", .min = 0.0F, .max = 100.0F, .description = "Speed of game time. 1 is normal, 0 stops it"} + ); + float max_delta = param( + &max_delta, "max_delta", 1.0F / 15.0F, + {.name = "Longest frame", + .min = 0.001F, + .max = 1.0F, + .unit = "s", + .description = "A slower frame is cut to this, so a hitch does not become a huge step"} + ); +}; + +TOAST_API auto timeParams() -> TimeParams&; + +} diff --git a/engine/src/toast/ui/ui_system.cpp b/engine/src/toast/ui/ui_system.cpp index aeb2240f5..17300dab3 100644 --- a/engine/src/toast/ui/ui_system.cpp +++ b/engine/src/toast/ui/ui_system.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include namespace ui { @@ -191,8 +192,45 @@ auto UISystem::exists() noexcept -> bool { return instance != nullptr; } +namespace { + +auto uiParameter(std::string_view path, float fallback) -> float { + const auto* param = toast::params::Registry::get().find(path); + if (param == nullptr) { + return fallback; + } + const auto value = param->snapshot(); + if (const auto* scalar = std::get_if(&value)) { + if (const auto* d = std::get_if(scalar)) { + return static_cast(*d); + } + if (const auto* i = std::get_if(scalar)) { + return static_cast(*i); + } + } + return fallback; +} + +} + void UISystem::tick() noexcept { ZoneScoped; + + { + const float scale = std::max(0.25F, uiParameter("ui.scale", 1.0F)); + const float scroll = std::max(0.05F, uiParameter("ui.scroll_speed", 1.0F)); + if (scale != m_ui_scale) { + m_ui_scale = scale; + applyDpRatio(m_dp_ratio); + } + if (scroll != m_scroll_speed) { + m_scroll_speed = scroll; + for (int i = 0; i < Rml::GetNumContexts(); ++i) { + Rml::GetContext(i)->SetDefaultScrollBehavior(Rml::ScrollBehavior::Instant, m_scroll_speed); + } + } + syncLanguageParameter(); + } { std::scoped_lock lock(m_deferred_mutex); for (auto& [_, setup] : m_deferred_setups) { @@ -252,7 +290,10 @@ auto UISystem::createContext(std::string_view name, glm::ivec2 dimensions, std:: return nullptr; } - context->SetDensityIndependentPixelRatio(fixed_dp_ratio.value_or(m_dp_ratio)); + context->SetDensityIndependentPixelRatio(fixed_dp_ratio.value_or(m_dp_ratio * m_ui_scale)); + if (m_scroll_speed != 1.0f) { + context->SetDefaultScrollBehavior(Rml::ScrollBehavior::Instant, m_scroll_speed); + } if (!fixed_dp_ratio.has_value()) { m_display_density_contexts.emplace(context); } @@ -264,7 +305,7 @@ auto UISystem::createContext(std::string_view name, glm::ivec2 dimensions, std:: void UISystem::applyDpRatio(float ratio) { m_dp_ratio = ratio; for (Rml::Context* context : m_display_density_contexts) { - context->SetDensityIndependentPixelRatio(ratio); + context->SetDensityIndependentPixelRatio(ratio * m_ui_scale); } } @@ -481,16 +522,72 @@ void UISystem::setLanguage(std::string language) { return; } } + switchLanguage(std::move(language)); +} + +void UISystem::switchLanguage(std::string language) { + ZoneScoped; if (language == currentLanguage()) { + publishLanguage(); return; } m_language = std::move(language); TOAST_INFO("UI", "Switching UI language to '{}'", m_language); + publishLanguage(); // Reloading re-runs TranslateString and re-applies localized images with the new language reloadAllDocuments(); } +void UISystem::publishLanguage() { + m_language_param_seen = currentLanguage(); + m_language_param_ready = true; + toast::params::Registry::get().request( + "ui.language", toast::params::Value {toast::params::Scalar {m_language_param_seen}}, toast::params::Layer::runtime + ); +} + +void UISystem::syncLanguageParameter() { + const auto& registry = toast::params::Registry::get(); + const auto* param = registry.find("ui.language"); + if (param == nullptr) { + return; + } + + const auto pending = registry.pendingValue("ui.language"); + const auto value = pending ? *pending : param->snapshot(); + const auto* scalar = std::get_if(&value); + const auto* text = scalar != nullptr ? std::get_if(scalar) : nullptr; + if (text == nullptr) { + return; + } + + if (!m_language_param_ready) { + m_language_param_ready = true; + if (text->empty()) { + publishLanguage(); + return; + } + } + if (*text == m_language_param_seen) { + return; + } + + m_language_param_seen = *text; + if (!text->empty()) { + switchLanguage(*text); + return; + } + std::string fallback = "en"; + if (toast::ProjectSettings::get() != nullptr) { + const auto& languages = toast::ProjectSettings::uiSettings().languages(); + if (!languages.empty()) { + fallback = languages.front(); + } + } + switchLanguage(std::move(fallback)); +} + void UISystem::reloadAllDocuments() { ZoneScoped; for (toast::Panel* panel : m_panels) { diff --git a/engine/src/toast/ui/ui_system.hpp b/engine/src/toast/ui/ui_system.hpp index 73c3558d4..43d3ea2f2 100644 --- a/engine/src/toast/ui/ui_system.hpp +++ b/engine/src/toast/ui/ui_system.hpp @@ -161,6 +161,10 @@ class UISystem { [[nodiscard]] auto currentLanguage() const -> std::string; + void switchLanguage(std::string language); + void publishLanguage(); + void syncLanguageParameter(); + static inline UISystem* instance = nullptr; std::unique_ptr m_file_interface; @@ -170,6 +174,8 @@ class UISystem { event::Listener m_asset_listener; float m_dp_ratio = 1.0f; + float m_ui_scale = 1.0f; + float m_scroll_speed = 1.0f; bool m_documents_reload_pending = false; bool m_stylesheet_cache_dirty = false; @@ -192,6 +198,8 @@ class UISystem { std::unordered_set m_loaded_fonts; std::string m_language; + std::string m_language_param_seen; + bool m_language_param_ready = false; std::vector> m_global_localizations; std::vector> m_global_image_localizations; std::unordered_map m_global_localization_refs; diff --git a/engine/src/toast/voxel/assets/voxel_thumbnail.cpp b/engine/src/toast/voxel/assets/voxel_thumbnail.cpp index be725c3a5..f904603f0 100644 --- a/engine/src/toast/voxel/assets/voxel_thumbnail.cpp +++ b/engine/src/toast/voxel/assets/voxel_thumbnail.cpp @@ -5,6 +5,7 @@ #include #include +#include namespace { @@ -12,8 +13,6 @@ using voxel::k_brick_dim; using voxel::k_empty_palette_index; using voxel::Palette; -constexpr uint32_t k_supersample = 4; - struct RgbaF { float r = 0.0f, g = 0.0f, b = 0.0f, a = 0.0f; }; @@ -259,6 +258,7 @@ auto toast_tvox_render_thumbnail(const char* tvox_path, const char* palette_path } const VoxThumbCamera cam = voxThumbBuildCamera(grid, *center_of_mass); + const uint32_t k_supersample = static_cast(voxel::voxelParams().thumbnail_supersample); const uint32_t super_size = thumb_size * k_supersample; std::vector samples(static_cast(super_size) * super_size); @@ -291,7 +291,7 @@ auto toast_tvox_render_thumbnail(const char* tvox_path, const char* palette_path a += s.a; } } - constexpr float k_samples_per_texel = static_cast(k_supersample * k_supersample); + const float k_samples_per_texel = static_cast(k_supersample * k_supersample); a /= k_samples_per_texel; if (a > 1e-6f) { const float inv_coverage_sum = 1.0f / (a * k_samples_per_texel); diff --git a/engine/src/toast/voxel/nodes/procedural_voxel.cpp b/engine/src/toast/voxel/nodes/procedural_voxel.cpp index 42b6fb400..70d62d81e 100644 --- a/engine/src/toast/voxel/nodes/procedural_voxel.cpp +++ b/engine/src/toast/voxel/nodes/procedural_voxel.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -641,7 +642,7 @@ void ProceduralVoxel::applyComposed(ComposeOutput& output) { "Voxel", "'{}' is missing voxels: the procedural brick pool is out of its {} bricks", name(), - voxel::k_procedural_brick_capacity + voxel::voxelParams().procedural_bricks ); } if (result.too_many_parts && !result.region.has_value()) { diff --git a/engine/src/toast/voxel/nodes/voxel_node.cpp b/engine/src/toast/voxel/nodes/voxel_node.cpp index 97519748b..bca693206 100644 --- a/engine/src/toast/voxel/nodes/voxel_node.cpp +++ b/engine/src/toast/voxel/nodes/voxel_node.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include namespace toast { @@ -152,7 +153,7 @@ auto VoxelNode::volume() -> voxel::Volume* { "Voxel", "'{}' could not be instantiated: the runtime brick pool is out of its {} bricks", name(), - voxel::k_runtime_brick_capacity + voxel::voxelParams().runtime_bricks ); } } @@ -267,13 +268,10 @@ void VoxelNode::finishShape() { namespace { -constexpr int32_t k_max_bricks_per_axis = 512; -constexpr int64_t k_max_bricks = int64_t {1} << 21; - [[nodiscard]] auto tooBig(glm::ivec3 dims) noexcept -> bool { - return glm::any(glm::greaterThan(dims, glm::ivec3(k_max_bricks_per_axis))) || - static_cast(dims.x) * dims.y * dims.z > k_max_bricks; + return glm::any(glm::greaterThan(dims, glm::ivec3(voxel::voxelParams().max_bricks_per_axis))) || + static_cast(dims.x) * dims.y * dims.z > voxel::voxelParams().max_bricks; } } @@ -296,8 +294,8 @@ auto VoxelNode::replaceVolume(const voxel::EditBounds& bounds) -> voxel::Volume* } auto VoxelNode::ensureContains(const voxel::EditBounds& bounds) -> voxel::Volume* { - constexpr int32_t max_bricks_per_axis = 512; - constexpr int64_t max_bricks = int64_t {1} << 21; + const int32_t max_bricks_per_axis = voxel::voxelParams().max_bricks_per_axis; + const int64_t max_bricks = voxel::voxelParams().max_bricks; voxel::Volume* current = volume(); if (bounds.empty()) { @@ -347,7 +345,7 @@ void VoxelNode::commitEdit(const voxel::EditResult& result, std::string_view ope "'{}' {} stopped early: the runtime brick pool is out of its {} bricks", name(), operation, - voxel::k_runtime_brick_capacity + voxel::voxelParams().runtime_bricks ); } if (result.changed == 0) { diff --git a/engine/src/toast/voxel/nodes/voxel_piece.cpp b/engine/src/toast/voxel/nodes/voxel_piece.cpp index f0cd783b5..dca8db8ff 100644 --- a/engine/src/toast/voxel/nodes/voxel_piece.cpp +++ b/engine/src/toast/voxel/nodes/voxel_piece.cpp @@ -5,6 +5,7 @@ #include #include +#include namespace toast { @@ -49,7 +50,7 @@ void VoxelPiece::draw(std::string_view operation, Kernel&& kernel) { "'{}' {} stopped early: the procedural brick pool is out of its {} bricks", name(), operation, - voxel::k_procedural_brick_capacity + voxel::voxelParams().procedural_bricks ); } } diff --git a/engine/src/toast/voxel/procedural_pool.cpp b/engine/src/toast/voxel/procedural_pool.cpp index 43c620006..f9335a999 100644 --- a/engine/src/toast/voxel/procedural_pool.cpp +++ b/engine/src/toast/voxel/procedural_pool.cpp @@ -1,9 +1,11 @@ #include "procedural_pool.hpp" +#include "voxel_params.hpp" + namespace voxel { auto proceduralBrickPool() -> BrickPool& { - static BrickPool* pool = new BrickPool(k_procedural_brick_capacity); + static BrickPool* pool = new BrickPool(static_cast(voxelParams().procedural_bricks)); return *pool; } diff --git a/engine/src/toast/voxel/procedural_pool.hpp b/engine/src/toast/voxel/procedural_pool.hpp index 320b265b3..e9892f722 100644 --- a/engine/src/toast/voxel/procedural_pool.hpp +++ b/engine/src/toast/voxel/procedural_pool.hpp @@ -13,8 +13,6 @@ namespace voxel { -inline constexpr uint32_t k_procedural_brick_capacity = 1u << 18; - /// @note Main thread only like the runtime pool [[nodiscard]] TOAST_API auto proceduralBrickPool() -> BrickPool&; diff --git a/engine/src/toast/voxel/runtime_pool.cpp b/engine/src/toast/voxel/runtime_pool.cpp index 499fad512..a830f7b25 100644 --- a/engine/src/toast/voxel/runtime_pool.cpp +++ b/engine/src/toast/voxel/runtime_pool.cpp @@ -1,10 +1,12 @@ #include "runtime_pool.hpp" +#include "voxel_params.hpp" + namespace voxel { auto runtimeBrickPool() -> BrickPool& { // Leaked since volumes free bricks in destructors that can run during static teardown - static BrickPool* pool = new BrickPool(k_runtime_brick_capacity); + static BrickPool* pool = new BrickPool(static_cast(voxelParams().runtime_bricks)); return *pool; } diff --git a/engine/src/toast/voxel/runtime_pool.hpp b/engine/src/toast/voxel/runtime_pool.hpp index 704e01dad..1acd2435e 100644 --- a/engine/src/toast/voxel/runtime_pool.hpp +++ b/engine/src/toast/voxel/runtime_pool.hpp @@ -14,8 +14,6 @@ namespace voxel { -inline constexpr uint32_t k_runtime_brick_capacity = 1u << 20; - /// @note Main thread only [[nodiscard]] TOAST_API auto runtimeBrickPool() -> BrickPool&; diff --git a/engine/src/toast/voxel/voxel_params.cpp b/engine/src/toast/voxel/voxel_params.cpp new file mode 100644 index 000000000..5cda3ef2c --- /dev/null +++ b/engine/src/toast/voxel/voxel_params.cpp @@ -0,0 +1,10 @@ +#include "voxel_params.hpp" + +namespace voxel { + +auto voxelParams() -> VoxelParams& { + static VoxelParams instance; + return instance; +} + +} diff --git a/engine/src/toast/voxel/voxel_params.hpp b/engine/src/toast/voxel/voxel_params.hpp new file mode 100644 index 000000000..395dcd3a9 --- /dev/null +++ b/engine/src/toast/voxel/voxel_params.hpp @@ -0,0 +1,57 @@ +/** + * @file voxel_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief How much memory voxels may take and how big + */ + +#pragma once +#include +#include +#include + +namespace voxel { + +struct VoxelParams : toast::params::Group<"voxel"> { + using Kind = toast::params::Kind; + + int32_t runtime_bricks = param( + &runtime_bricks, "pools.runtime_bricks", 1 << 20, + {.name = "Runtime bricks", + .min = 1 << 12, + .max = 1 << 24, + .unit = "bricks", + .description = "Room for the voxels of everything in the scene", + .requires_restart = true} + ); + int32_t procedural_bricks = param( + &procedural_bricks, "pools.procedural_bricks", 1 << 18, + {.name = "Procedural bricks", + .min = 1 << 10, + .max = 1 << 24, + .unit = "bricks", + .description = "Room for generated voxels", + .requires_restart = true} + ); + int32_t max_bricks_per_axis = param( + &max_bricks_per_axis, "limits.max_bricks_per_axis", 512, + {.name = "Longest side", .min = 8, .max = 4096, .unit = "bricks", .description = "Larger volumes are refused"} + ); + int64_t max_bricks = param( + &max_bricks, "limits.max_bricks", int64_t {1} << 21, + {.name = "Volume size", + .min = int64_t {1} << 10, + .max = int64_t {1} << 28, + .unit = "bricks", + .description = "Volumes with more bricks than this are refused"} + ); + int32_t thumbnail_supersample = param( + &thumbnail_supersample, "thumbnails.supersample", 4, + {.name = "Thumbnail samples", .min = 1, .max = 8, .description = "Samples per pixel side. More is smoother and slower"} + ); +}; + +TOAST_API auto voxelParams() -> VoxelParams&; + +} diff --git a/engine/src/toast/window/sdl_window.cpp b/engine/src/toast/window/sdl_window.cpp index 67e1bc57b..ef29ea16d 100644 --- a/engine/src/toast/window/sdl_window.cpp +++ b/engine/src/toast/window/sdl_window.cpp @@ -1,6 +1,7 @@ #include "sdl_window.hpp" #include +#include namespace { @@ -130,6 +131,17 @@ void SDLWindow::pollEvents() { } }; + { + const bool console_open = toast::console::Console::get().isOpen(); + SDL_Window* window = m.sdl_window.get(); + if (console_open && !m.console_text_input) { + m.console_text_input = !SDL_TextInputActive(window) && SDL_StartTextInput(window); + } else if (!console_open && m.console_text_input) { + m.console_text_input = false; + SDL_StopTextInput(window); + } + } + const SDL_WindowID window_id = SDL_GetWindowID(m.sdl_window.get()); for (SDL_Event event; SDL_PollEvent(&event);) { ZoneScopedN("SDLWindow::event"); diff --git a/engine/src/toast/window/sdl_window.hpp b/engine/src/toast/window/sdl_window.hpp index 7c5547af0..9ccca3fc5 100644 --- a/engine/src/toast/window/sdl_window.hpp +++ b/engine/src/toast/window/sdl_window.hpp @@ -51,6 +51,7 @@ class SDLWindow : public IBaseWindow { event::Listener event_listener; bool should_close = false; bool cursor_locked = false; + bool console_text_input = false; bool lock_requested = false; bool overlay_cursor = false; glm::vec2 virtual_mouse_position {0.0f}; diff --git a/engine/src/toast/world/editor_camera.cpp b/engine/src/toast/world/editor_camera.cpp index 7de469111..5f043c098 100644 --- a/engine/src/toast/world/editor_camera.cpp +++ b/engine/src/toast/world/editor_camera.cpp @@ -75,9 +75,17 @@ void EditorCameraController::copyViewFrom(const EditorCameraController& other) n m_mode = other.m_mode; } +void EditorCameraController::placeAt(glm::vec3 position, const glm::quat& rotation) noexcept { + const glm::vec3 forward = rotation * Camera::world_forward; + m_mode = event::EditorCameraMode::free; + m_position = position; + m_yaw = std::atan2(-forward.x, forward.y); + m_pitch = std::clamp(std::asin(std::clamp(forward.z, -1.0f, 1.0f)), -k_pitch_limit, k_pitch_limit); +} + void EditorCameraController::configure(event::EditorCameraMode mode, float speed, bool horizontal_movement) { setMode(mode); - m_speed = std::clamp(speed, k_min_speed, k_max_speed); + m_speed = clampedBetween(speed, editorParams().camera_min_speed, editorParams().camera_max_speed); m_horizontal_movement = horizontal_movement; } @@ -95,8 +103,9 @@ void EditorCameraController::setMode(event::EditorCameraMode mode) { } void EditorCameraController::syncOrbitFromPosition() { - m_orbit_radius = std::clamp(glm::length(m_position), k_min_radius, k_max_radius); - if (m_orbit_radius > k_min_radius) { + m_orbit_radius = + clampedBetween(glm::length(m_position), editorParams().camera_orbit_min_radius, editorParams().camera_orbit_max_radius); + if (m_orbit_radius > editorParams().camera_orbit_min_radius) { m_yaw = std::atan2(m_position.x, -m_position.y); m_orbit_elevation = std::clamp(std::asin(m_position.z / m_orbit_radius), -k_pitch_limit, k_pitch_limit); } @@ -108,11 +117,12 @@ auto EditorCameraController::orientation() const -> glm::quat { } void EditorCameraController::applyLook(float dx, float dy) { - m_yaw -= dx * k_look_sensitivity; + m_yaw -= dx * editorParams().camera_look_sensitivity; if (m_mode == event::EditorCameraMode::orbit) { - m_orbit_elevation = std::clamp(m_orbit_elevation + (dy * k_look_sensitivity), -k_pitch_limit, k_pitch_limit); + m_orbit_elevation = + std::clamp(m_orbit_elevation + (dy * editorParams().camera_look_sensitivity), -k_pitch_limit, k_pitch_limit); } else { - m_pitch = std::clamp(m_pitch - (dy * k_look_sensitivity), -k_pitch_limit, k_pitch_limit); + m_pitch = std::clamp(m_pitch - (dy * editorParams().camera_look_sensitivity), -k_pitch_limit, k_pitch_limit); } } @@ -125,7 +135,7 @@ void EditorCameraController::applyPan(float dx, float dy) { const glm::quat rot = orientation(); const glm::vec3 right = rot * glm::vec3(1.0f, 0.0f, 0.0f); const glm::vec3 up = rot * Camera::world_up; - m_position += ((right * -dx) + (up * dy)) * k_gesture_pan_sensitivity * m_speed; + m_position += ((right * -dx) + (up * dy)) * editorParams().camera_pan_sensitivity * m_speed; } void EditorCameraController::applyZoom(float delta) { @@ -133,11 +143,15 @@ void EditorCameraController::applyZoom(float delta) { return; } if (m_mode == event::EditorCameraMode::orbit) { - m_orbit_radius = std::clamp(m_orbit_radius * std::exp(-delta * k_gesture_zoom_sensitivity), k_min_radius, k_max_radius); + m_orbit_radius = clampedBetween( + m_orbit_radius * std::exp(-delta * editorParams().camera_zoom_sensitivity), + editorParams().camera_orbit_min_radius, + editorParams().camera_orbit_max_radius + ); return; } - m_position += (orientation() * Camera::world_forward) * delta * m_speed * k_gesture_zoom_sensitivity; + m_position += (orientation() * Camera::world_forward) * delta * m_speed * editorParams().camera_zoom_sensitivity; } void EditorCameraController::tick(float dt, Camera* target) { @@ -146,8 +160,8 @@ void EditorCameraController::tick(float dt, Camera* target) { } if (m_mode == event::EditorCameraMode::orbit) { - const float speed = m_speed * (m_boost ? k_boost_multiplier : 1.0f); - const float angular_speed = speed / std::max(m_orbit_radius, k_min_radius); + const float speed = m_speed * (m_boost ? editorParams().camera_boost : 1.0f); + const float angular_speed = speed / std::max(m_orbit_radius, editorParams().camera_orbit_min_radius); if (m_move_forward) { m_orbit_elevation += angular_speed * dt; } @@ -167,7 +181,8 @@ void EditorCameraController::tick(float dt, Camera* target) { m_orbit_radius -= speed * dt; } m_orbit_elevation = std::clamp(m_orbit_elevation, -k_pitch_limit, k_pitch_limit); - m_orbit_radius = std::clamp(m_orbit_radius, k_min_radius, k_max_radius); + m_orbit_radius = + clampedBetween(m_orbit_radius, editorParams().camera_orbit_min_radius, editorParams().camera_orbit_max_radius); const float horizontal = std::cos(m_orbit_elevation) * m_orbit_radius; m_position = { @@ -213,7 +228,7 @@ void EditorCameraController::tick(float dt, Camera* target) { if (glm::length(move) > 0.0001f) { move = glm::normalize(move); - const float speed = m_speed * (m_boost ? k_boost_multiplier : 1.0f); + const float speed = m_speed * (m_boost ? editorParams().camera_boost : 1.0f); m_position += move * speed * dt; } diff --git a/engine/src/toast/world/editor_camera.hpp b/engine/src/toast/world/editor_camera.hpp index 8174aaa47..942dbc6bf 100644 --- a/engine/src/toast/world/editor_camera.hpp +++ b/engine/src/toast/world/editor_camera.hpp @@ -6,6 +6,7 @@ #pragma once #include "camera.hpp" +#include "editor_params.hpp" #include "workspace_events.hpp" #include @@ -33,6 +34,8 @@ class TOAST_API EditorCameraController { void copyViewFrom(const EditorCameraController& other) noexcept; + void placeAt(glm::vec3 position, const glm::quat& rotation) noexcept; + [[nodiscard]] auto mode() const noexcept -> event::EditorCameraMode { return m_mode; @@ -77,18 +80,10 @@ class TOAST_API EditorCameraController { float m_orbit_elevation = 0.0f; float m_orbit_radius = 0.0f; - float m_speed = 5.0f; + float m_speed = editorParams().camera_default_speed; bool m_horizontal_movement = false; event::EditorCameraMode m_mode = event::EditorCameraMode::free; - static constexpr float k_min_speed = 0.5f; - static constexpr float k_max_speed = 50.0f; - static constexpr float k_min_radius = 0.1f; - static constexpr float k_max_radius = 5000.0f; - static constexpr float k_boost_multiplier = 3.0f; - static constexpr float k_look_sensitivity = 0.0025f; - static constexpr float k_gesture_zoom_sensitivity = 0.01f; - static constexpr float k_gesture_pan_sensitivity = 0.01f; static constexpr float k_pitch_limit = 1.5533f; // ~89 degrees void setMode(event::EditorCameraMode mode); diff --git a/engine/src/toast/world/editor_params.cpp b/engine/src/toast/world/editor_params.cpp new file mode 100644 index 000000000..479fb6481 --- /dev/null +++ b/engine/src/toast/world/editor_params.cpp @@ -0,0 +1,10 @@ +#include "editor_params.hpp" + +namespace toast { + +auto editorParams() -> EditorParams& { + static EditorParams instance; + return instance; +} + +} diff --git a/engine/src/toast/world/editor_params.hpp b/engine/src/toast/world/editor_params.hpp new file mode 100644 index 000000000..6286de9f4 --- /dev/null +++ b/engine/src/toast/world/editor_params.hpp @@ -0,0 +1,162 @@ +/** + * @file editor_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief How someone likes the editor to behave + */ + +#pragma once +#include +#include +#include + +namespace toast { + +struct EditorParams : params::Group<"editor"> { + using Kind = params::Kind; + + float camera_default_speed = param( + &camera_default_speed, "camera.default_speed", 5.0F, + {.name = "Start speed", + .min = 0.1F, + .max = 500.0F, + .unit = "m/s", + .kind = Kind::user, + .description = "Fly speed a new viewport starts at"} + ); + float camera_min_speed = param( + &camera_min_speed, "camera.min_speed", 0.5F, + {.name = "Slowest speed", + .min = 0.01F, + .max = 100.0F, + .unit = "m/s", + .kind = Kind::user, + .description = "The slowest the scroll wheel goes"} + ); + float camera_max_speed = param( + &camera_max_speed, "camera.max_speed", 50.0F, + {.name = "Fastest speed", + .min = 1.0F, + .max = 5000.0F, + .unit = "m/s", + .kind = Kind::user, + .description = "The fastest the scroll wheel goes"} + ); + float camera_boost = param( + &camera_boost, "camera.boost", 3.0F, + {.name = "Boost", + .min = 1.0F, + .max = 50.0F, + .kind = Kind::user, + .description = "Speed multiplier while the boost key is held"} + ); + float camera_look_sensitivity = param( + &camera_look_sensitivity, "camera.look_sensitivity", 0.0025F, + {.name = "Look sensitivity", + .min = 0.0002F, + .max = 0.05F, + .kind = Kind::user, + .description = "Radians turned per pixel of mouse"} + ); + float camera_zoom_sensitivity = param( + &camera_zoom_sensitivity, "camera.zoom_sensitivity", 0.01F, + {.name = "Zoom sensitivity", .min = 0.001F, .max = 0.5F, .kind = Kind::user} + ); + float camera_pan_sensitivity = param( + &camera_pan_sensitivity, "camera.pan_sensitivity", 0.01F, + {.name = "Pan sensitivity", .min = 0.001F, .max = 0.5F, .kind = Kind::user} + ); + float camera_orbit_min_radius = param( + &camera_orbit_min_radius, "camera.orbit_min_radius", 0.1F, + {.name = "Closest orbit", + .min = 0.01F, + .max = 10.0F, + .unit = "m", + .kind = Kind::user, + .description = "Closest an orbiting camera gets to its target"} + ); + bool autosave_enabled = param( + &autosave_enabled, "autosave.enabled", true, + {.name = "Autosave", .kind = Kind::user, .description = "Keep a copy of unsaved work to recover from a crash"} + ); + int autosave_interval = param( + &autosave_interval, "autosave.interval_seconds", 60, + {.name = "Autosave every", .min = 10, .max = 3600, .unit = "s", .kind = Kind::user, .description = "Between autosaves"} + ); + int git_fetch_interval = param( + &git_fetch_interval, "git.fetch_seconds", 300, + {.name = "Fetch every", + .min = 10, + .max = 7200, + .unit = "s", + .kind = Kind::user, + .description = "Between checks for new commits"} + ); + int git_locks_interval = param( + &git_locks_interval, "git.locks_seconds", 60, + {.name = "Refresh locks every", + .min = 10, + .max = 600, + .unit = "s", + .kind = Kind::user, + .description = "Between lock refreshes"} + ); + bool snap_translate_enabled = param( + &snap_translate_enabled, "snapping.translate_enabled", true, + {.name = "Move snapping", .kind = Kind::user, .description = "On for a new viewport"} + ); + float snap_translate_step = param( + &snap_translate_step, "snapping.translate_step", 0.1F, + {.name = "Move step", + .min = 0.001F, + .max = 100.0F, + .unit = "m", + .kind = Kind::user, + .description = "Where a new viewport starts"} + ); + bool snap_rotate_enabled = param( + &snap_rotate_enabled, "snapping.rotate_enabled", true, + {.name = "Rotate snapping", .kind = Kind::user, .description = "On for a new viewport"} + ); + float snap_rotate_step = param( + &snap_rotate_step, "snapping.rotate_step", 30.0F, + {.name = "Rotate step", + .min = 0.1F, + .max = 180.0F, + .unit = "°", + .kind = Kind::user, + .description = "Where a new viewport starts"} + ); + bool snap_scale_enabled = param( + &snap_scale_enabled, "snapping.scale_enabled", true, + {.name = "Scale snapping", .kind = Kind::user, .description = "On for a new viewport"} + ); + float snap_scale_step = param( + &snap_scale_step, "snapping.scale_step", 0.1F, + {.name = "Scale step", .min = 0.001F, .max = 10.0F, .kind = Kind::user, .description = "Where a new viewport starts"} + ); + int logs_message_length = param( + &logs_message_length, "logs.max_message_length", 500, + {.name = "Longest log line", + .min = 80, + .max = 5000, + .unit = "chars", + .kind = Kind::user, + .description = "Longer log lines are cut in the list"} + ); + float camera_orbit_max_radius = param( + &camera_orbit_max_radius, "camera.orbit_max_radius", 5000.0F, + {.name = "Farthest orbit", .min = 10.0F, .max = 100000.0F, .unit = "m", .kind = Kind::user} + ); +}; + +[[nodiscard]] +inline auto clampedBetween(float value, float low, float high) -> float { + return std::clamp(value, low, std::max(low, high)); +} + +[[nodiscard]] +TOAST_API auto editorParams() -> EditorParams&; + +} diff --git a/engine/src/toast/world/fly_camera.cpp b/engine/src/toast/world/fly_camera.cpp new file mode 100644 index 000000000..a5cc458a8 --- /dev/null +++ b/engine/src/toast/world/fly_camera.cpp @@ -0,0 +1,120 @@ +#include "fly_camera.hpp" + +#include "workspace_events.hpp" + +#include +#include +#include +#include + +namespace toast { +namespace { + +constexpr int k_right_button = 3; + +auto parameterOn() -> bool { + const auto* param = params::Registry::get().find("renderer.editor_camera"); + if (param == nullptr) { + return false; + } + const auto value = param->snapshot(); + if (const auto* scalar = std::get_if(&value)) { + if (const auto* on = std::get_if(scalar)) { + return *on; + } + } + return false; +} + +} + +FlyCamera::FlyCamera() : m_camera(std::make_unique()) { + m_listener.subscribe([this](const event::WindowKey& e) { + if (!m_flying) { + return false; + } + const bool down = e.action != event::window_input_released; + bool* target = nullptr; + switch (e.key) { + case SDLK_W: target = &m_forward; break; + case SDLK_S: target = &m_back; break; + case SDLK_A: target = &m_left; break; + case SDLK_D: target = &m_right; break; + case SDLK_E: target = &m_up; break; + case SDLK_Q: target = &m_down; break; + case SDLK_LSHIFT: + case SDLK_RSHIFT: target = &m_boost; break; + default: return false; + } + *target = down; + sendMovement(); + return true; + }); + + m_listener.subscribe([this](const event::WindowMouseButton& e) { + if (!m_flying || e.button != k_right_button) { + return false; + } + m_looking = e.action != event::window_input_released; + event::send(m_looking); + return true; + }); + + m_listener.subscribe([this](const event::WindowMousePosition& e) { + const float dx = e.x - m_mouse_x; + const float dy = e.y - m_mouse_y; + const bool had_mouse = m_have_mouse; + m_mouse_x = e.x; + m_mouse_y = e.y; + m_have_mouse = true; + if (!m_flying || !m_looking || !had_mouse) { + return false; + } + event::send(dx, dy); + return true; + }); +} + +FlyCamera::~FlyCamera() { + stop(); +} + +void FlyCamera::sendMovement() const { + event::send(m_forward, m_back, m_left, m_right, m_up, m_down, m_boost); +} + +void FlyCamera::start() { + m_flying = true; + m_forward = m_back = m_left = m_right = m_up = m_down = m_boost = false; + m_looking = false; + + if (const Camera* current = renderer::getActiveCamera(); current != nullptr && current != m_camera.get()) { + m_controller.placeAt(current->world_position, current->world_rotation); + } + m_controller.setEnabled(true); + m_controller.tick(0.0F, m_camera.get()); + renderer::setCameraOverride(m_camera.get()); +} + +void FlyCamera::stop() { + if (!m_flying) { + return; + } + m_flying = false; + m_controller.setEnabled(false); + renderer::setCameraOverride(nullptr); +} + +void FlyCamera::tick(float dt) { + const bool wanted = parameterOn(); + if (wanted && !m_flying) { + start(); + } else if (!wanted && m_flying) { + stop(); + } + if (m_flying) { + m_controller.tick(dt, m_camera.get()); + } +} + +} diff --git a/engine/src/toast/world/fly_camera.hpp b/engine/src/toast/world/fly_camera.hpp new file mode 100644 index 000000000..a12228821 --- /dev/null +++ b/engine/src/toast/world/fly_camera.hpp @@ -0,0 +1,56 @@ +/** + * @file fly_camera.hpp + * @author Xein + * @date 25 Nov 2026 + * + * @brief The editor's fly camera + */ + +#pragma once +#include "camera.hpp" +#include "editor_camera.hpp" + +#include +#include +#include + +namespace toast { + +class TOAST_API FlyCamera { +public: + FlyCamera(); + ~FlyCamera(); + + FlyCamera(const FlyCamera&) = delete; + auto operator=(const FlyCamera&) -> FlyCamera& = delete; + + void tick(float dt); + + [[nodiscard]] + auto flying() const -> bool { + return m_flying; + } + +private: + void start(); + void stop(); + void sendMovement() const; + + std::unique_ptr m_camera; + EditorCameraController m_controller; + event::Listener m_listener; + bool m_flying = false; + bool m_looking = false; + bool m_have_mouse = false; + float m_mouse_x = 0.0F; + float m_mouse_y = 0.0F; + bool m_forward = false; + bool m_back = false; + bool m_left = false; + bool m_right = false; + bool m_up = false; + bool m_down = false; + bool m_boost = false; +}; + +} diff --git a/engine/src/toast/world/tick_scheduler.cpp b/engine/src/toast/world/tick_scheduler.cpp index d6f81ee79..44f019375 100644 --- a/engine/src/toast/world/tick_scheduler.cpp +++ b/engine/src/toast/world/tick_scheduler.cpp @@ -10,6 +10,8 @@ #include #include #include +#include +#include namespace toast { @@ -380,8 +382,6 @@ void TickScheduler::runPhase(const std::vector& phase, TickF namespace { -constexpr size_t k_min_scripts_for_parallel_lifecycle = 16; - // tf is this auto serialLifecycleRequested() -> bool { static const bool requested = [] { @@ -441,7 +441,7 @@ void TickScheduler::runLifecycle(Node& root, TickFunctionList stage) const { }; count(root); } - if (scripted < k_min_scripts_for_parallel_lifecycle || interpreters.size() < 2) { + if (std::cmp_less(scripted, scripting::scriptingParams().parallel_lifecycle) || interpreters.size() < 2) { one_node_at_a_time(); return; } diff --git a/engine/src/toast/world/wave_executor.cpp b/engine/src/toast/world/wave_executor.cpp index 636efad4d..c8c4738e9 100644 --- a/engine/src/toast/world/wave_executor.cpp +++ b/engine/src/toast/world/wave_executor.cpp @@ -5,6 +5,7 @@ #endif #include #include +#include namespace toast::_detail { @@ -19,9 +20,6 @@ inline void cpuRelax() noexcept { } std::atomic g_queued_helpers {0}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) -constexpr size_t k_queued_helpers_per_worker = 4; -constexpr auto k_grace_with_idle_workers = std::chrono::milliseconds(2); -constexpr auto k_grace_without_idle_workers = std::chrono::microseconds(150); struct alignas(64) Claim { std::atomic next {0}; @@ -150,7 +148,7 @@ void runJobs(const std::vector& jobs, size_t item_count, ItemRunner run const size_t workers = ThreadPool::workerCount(); const size_t idle = ThreadPool::idleWorkers(); const size_t helpers = std::min(jobs.size(), workers); - const size_t queue_limit = workers * k_queued_helpers_per_worker; + const size_t queue_limit = workers * static_cast(worldParams().queued_helpers_per_worker); size_t queued = 0; for (; queued < helpers; ++queued) { if (g_queued_helpers.fetch_add(1) >= queue_limit) { @@ -172,8 +170,8 @@ void runJobs(const std::vector& jobs, size_t item_count, ItemRunner run work(); } else { // Workers that are waiting for a task show up at once - const auto deadline = - std::chrono::steady_clock::now() + (idle != 0 ? k_grace_with_idle_workers : k_grace_without_idle_workers); + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::microseconds(idle != 0 ? worldParams().grace_idle : worldParams().grace_busy); unsigned spins = 0; while (run->remaining.load() != 0 && run->entered.load(std::memory_order_relaxed) == 0) { if (std::chrono::steady_clock::now() >= deadline) { diff --git a/engine/src/toast/world/workspace.hpp b/engine/src/toast/world/workspace.hpp index c13af2124..ff4deb456 100644 --- a/engine/src/toast/world/workspace.hpp +++ b/engine/src/toast/world/workspace.hpp @@ -330,6 +330,11 @@ class TOAST_API Workspace : public INodeOwner { return *m_root_node; } + [[nodiscard]] + auto rootBox() const -> Box { + return m_root_node; + } + [[nodiscard]] auto isValid() const -> bool { return m_root_node.exists(); diff --git a/engine/src/toast/world/world.cpp b/engine/src/toast/world/world.cpp index 3b2519b7e..553e7b041 100644 --- a/engine/src/toast/world/world.cpp +++ b/engine/src/toast/world/world.cpp @@ -632,6 +632,14 @@ auto World::cacheNode(Node& node) -> Box { return instance->moveToCached(node); } +auto World::root() -> Box { + if (instance == nullptr) { + return {}; + } + const TreeReadLock lock(instance); + return instance->trees.root; +} + auto World::findCached(std::string_view name) -> Box { ZoneScoped; diff --git a/engine/src/toast/world/world.hpp b/engine/src/toast/world/world.hpp index 9d8ca2554..6da3a80d8 100644 --- a/engine/src/toast/world/world.hpp +++ b/engine/src/toast/world/world.hpp @@ -105,6 +105,9 @@ class World final : public INodeOwner { */ static void destroyNode(Node& node); + [[nodiscard]] + static auto root() -> Box; + /** * @brief Linear search for a cached root node by display name * @param name The node's display name to search for diff --git a/engine/src/toast/world/world_params.cpp b/engine/src/toast/world/world_params.cpp new file mode 100644 index 000000000..fe1c8763c --- /dev/null +++ b/engine/src/toast/world/world_params.cpp @@ -0,0 +1,10 @@ +#include "world_params.hpp" + +namespace toast { + +auto worldParams() -> WorldParams& { + static WorldParams instance; + return instance; +} + +} diff --git a/engine/src/toast/world/world_params.hpp b/engine/src/toast/world/world_params.hpp new file mode 100644 index 000000000..1084e9e8b --- /dev/null +++ b/engine/src/toast/world/world_params.hpp @@ -0,0 +1,49 @@ +/** + * @file world_params.hpp + * @author Xein + * @date 24 Nov 2026 + * + * @brief How the world ticks its nodes across threads + */ + +#pragma once +#include +#include +#include + +namespace toast { + +struct WorldParams : params::Group<"world"> { + using Kind = params::Kind; + + int32_t queued_helpers_per_worker = param( + &queued_helpers_per_worker, "scheduler.queued_helpers", 4, + {.name = "Helpers per worker", + .min = 1, + .max = 64, + .kind = Kind::advanced, + .description = "Jobs a wave queues for each worker thread"} + ); + int32_t grace_idle = param( + &grace_idle, "scheduler.grace_idle", 2000, + {.name = "Grace with idle workers", + .min = 0, + .max = 20000, + .unit = "µs", + .kind = Kind::advanced, + .description = "How long a wave waits for a helper while some are free"} + ); + int32_t grace_busy = param( + &grace_busy, "scheduler.grace_busy", 150, + {.name = "Grace with busy workers", + .min = 0, + .max = 20000, + .unit = "µs", + .kind = Kind::advanced, + .description = "How long a wave waits for a helper while all are busy"} + ); +}; + +TOAST_API auto worldParams() -> WorldParams&; + +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4c581a3d6..c5af6ab4f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -18,7 +18,7 @@ if (BUILD_TESTING) target_precompile_headers(toast_tests PRIVATE ${CMAKE_SOURCE_DIR}/engine/pch.h) # renderer/04-import-reflection calls the Slang API directly and the engine find_package does not carry here find_package(slang CONFIG REQUIRED) - target_link_libraries(toast_tests PRIVATE toast_engine RmlUi::RmlUi slang::slang unofficial::sqlite3::sqlite3) + target_link_libraries(toast_tests PRIVATE toast_engine toast_pack RmlUi::RmlUi slang::slang unofficial::sqlite3::sqlite3) target_compile_definitions(toast_tests PRIVATE UNIT_TESTING TRACY_NO_INVARIANT_CHECK=1) target_compile_definitions(toast_tests PRIVATE TOAST_CORE_ASSETS_DIR="${CMAKE_SOURCE_DIR}/engine/assets") target_compile_definitions(toast_tests PRIVATE TOAST_TEST_CONTENT_DIR="${CMAKE_SOURCE_DIR}/tools/test_content") diff --git a/tests/settings/01-layers.cpp b/tests/settings/01-layers.cpp deleted file mode 100644 index b0a6ace07..000000000 --- a/tests/settings/01-layers.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include "toast/settings/settings.hpp" - -#include "test_registry.hpp" - -#include -#include -#include - -using namespace toast::settings; - -namespace { - -auto tempDir() -> std::filesystem::path { - auto dir = std::filesystem::temp_directory_path() / "toast_settings_layers"; - std::filesystem::remove_all(dir); - std::filesystem::create_directories(dir); - return dir; -} - -auto readAll(const std::filesystem::path& path) -> std::string { - std::ifstream in(path); - return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; -} - -} - -/// The layering rule the whole design rests on: the editor authors project defaults, a player's own tweaks go -/// in the user layer on top, and a save writes only the layer being edited -TOAST_TEST_NAMED("settings", "settings/01-layers", test_settings_01_layers) { - const auto dir = tempDir(); - const auto project_file = dir / "settings.toml"; - const auto user_file = dir / "user" / "settings.toml"; - - auto& settings = Settings::get(); - settings.setPaths(project_file, user_file); - - auto quality = declareInt("test.layers.quality", 1, {.label = "Quality"}); - auto enabled = declareBool("test.layers.enabled", true); - - assert(quality.value() == 1); - assert(enabled.value() == true); - - // Editor: authoring the defaults that ship - settings.setActiveLayer(Layer::project); - quality.set(3); - assert(quality.value() == 3); - assert(settings.save()); - assert(std::filesystem::exists(project_file)); - - const auto project_text = readAll(project_file); - assert(project_text.find("quality") != std::string::npos); - assert(project_text.find("enabled") != std::string::npos); - - // Packaged game: a player's tweak lands on top without touching what shipped - settings.setActiveLayer(Layer::user); - quality.set(0); - assert(quality.value() == 0); - assert(settings.save()); - assert(std::filesystem::exists(user_file)); - - // The project file still says what the editor authored - assert(readAll(project_file).find("quality") != std::string::npos); - - // Dropping the user override exposes the project value underneath rather than the code default - assert(settings.reset("test.layers.quality")); - assert(quality.value() == 3); - - // And dropping the project override falls the rest of the way to the code default - settings.setActiveLayer(Layer::project); - assert(settings.reset("test.layers.quality")); - assert(quality.value() == 1); - - std::filesystem::remove_all(dir); -} diff --git a/tests/settings/02-undeclared-keys.cpp b/tests/settings/02-undeclared-keys.cpp deleted file mode 100644 index 23b5ca4a2..000000000 --- a/tests/settings/02-undeclared-keys.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "toast/settings/settings.hpp" - -#include "test_registry.hpp" - -#include -#include -#include - -using namespace toast::settings; - -namespace { - -auto tempDir() -> std::filesystem::path { - auto dir = std::filesystem::temp_directory_path() / "toast_settings_undeclared"; - std::filesystem::remove_all(dir); - std::filesystem::create_directories(dir); - return dir; -} - -auto readAll(const std::filesystem::path& path) -> std::string { - std::ifstream in(path); - return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; -} - -} - -/// The layering rule the whole design rests on: the editor authors project defaults, a player's own tweaks go -/// in the user layer on top, and a save writes only the layer being edited -/// A settings file outlives the code that reads it: a key may belong to a system not constructed yet, and it -/// has to survive both the load that could not type it and the save that never saw it declared -TOAST_TEST_NAMED("settings", "settings/02-undeclared-keys", test_settings_02_undeclared) { - const auto dir = tempDir(); - const auto project_file = dir / "settings.toml"; - const auto user_file = dir / "user" / "settings.toml"; - - { - std::ofstream out(project_file); - out << "name = \"Settings Test\"\ndatabases = [\"assets\", \"dlc\"]\n" - "[test.pending]\nlate = 7\nforeign = \"kept\"\n"; - } - - auto& settings = Settings::get(); - settings.setPaths(project_file, user_file); - settings.setActiveLayer(Layer::project); - settings.load(); - - // Declared after the file was read: the stored value still reaches it - auto late = declareInt("test.pending.late", 1); - assert(late.value() == 7); - - // Nothing declares this one, and a save must not prune it - assert(settings.save()); - const auto project_text = readAll(project_file); - assert(project_text.find("foreign") != std::string::npos); - assert(project_text.find("Settings Test") != std::string::npos); - assert(project_text.find("databases") != std::string::npos); - assert(project_text.find("assets") != std::string::npos); - assert(project_text.find("dlc") != std::string::npos); - - std::filesystem::remove_all(dir); -} diff --git a/tests/settings/03-on-change.cpp b/tests/settings/03-on-change.cpp deleted file mode 100644 index c6ff757d6..000000000 --- a/tests/settings/03-on-change.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include "toast/settings/settings.hpp" - -#include "test_registry.hpp" - -#include -#include -#include - -using namespace toast::settings; - -namespace { - -auto tempDir() -> std::filesystem::path { - auto dir = std::filesystem::temp_directory_path() / "toast_settings_on_change"; - std::filesystem::remove_all(dir); - std::filesystem::create_directories(dir); - return dir; -} - -} - -/// The layering rule the whole design rests on: the editor authors project defaults, a player's own tweaks go -/// in the user layer on top, and a save writes only the layer being edited -/// onChange is how a system applies a setting, so it has to fire once at declaration - otherwise a stored -/// value only takes effect after the user edits it again -TOAST_TEST_NAMED("settings", "settings/03-on-change", test_settings_03_on_change) { - const auto dir = tempDir(); - auto& settings = Settings::get(); - settings.setPaths(dir / "settings.toml", dir / "user" / "settings.toml"); - settings.setActiveLayer(Layer::project); - - auto volume = declareFloat("test.change.volume", 0.5); - - int calls = 0; - double last = -1.0; - volume.onChange([&](double v) { - ++calls; - last = v; - }); - - assert(calls == 1); - assert(last == 0.5); - - volume.set(0.25); - assert(calls == 2); - assert(last == 0.25); - - // Setting the same value again is not a change, and re-applying it would have systems rebuild for nothing - volume.set(0.25); - assert(calls == 2); - - std::filesystem::remove_all(dir); -} diff --git a/tests/settings/04-coercion.cpp b/tests/settings/04-coercion.cpp deleted file mode 100644 index 6499bab37..000000000 --- a/tests/settings/04-coercion.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include "toast/settings/settings.hpp" - -#include "test_registry.hpp" - -#include -#include -#include - -using namespace toast::settings; - -namespace { - -auto tempDir() -> std::filesystem::path { - auto dir = std::filesystem::temp_directory_path() / "toast_settings_coercion"; - std::filesystem::remove_all(dir); - std::filesystem::create_directories(dir); - return dir; -} - -auto readAll(const std::filesystem::path& path) -> std::string { - std::ifstream in(path); - return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; -} - -} - -/// The layering rule the whole design rests on: the editor authors project defaults, a player's own tweaks go -/// in the user layer on top, and a save writes only the layer being edited -/// TOML gives back whatever the file literally held, so an integer written for a float setting has to widen -/// rather than be rejected - a hand-edited file writing `1` instead of `1.0` is the normal case -TOAST_TEST_NAMED("settings", "settings/04-coercion", test_settings_04_coercion) { - const auto dir = tempDir(); - const auto project_file = dir / "settings.toml"; - - { - std::ofstream out(project_file); - out << "[test.coerce]\nratio = 2\n"; - } - - auto& settings = Settings::get(); - settings.setPaths(project_file, dir / "user" / "settings.toml"); - settings.setActiveLayer(Layer::project); - settings.load(); - - auto ratio = declareFloat("test.coerce.ratio", 0.0); - assert(ratio.value() == 2.0); - - // A string against a number is a genuinely wrong file, not a formatting accident - assert(!settings.setValue("test.coerce.ratio", Value {std::string {"nope"}})); - assert(ratio.value() == 2.0); - - std::filesystem::remove_all(dir); -}