diff --git a/docs/asset_specs.md b/docs/asset_specs.md index 2af5ab8da..b7af5a9d7 100644 --- a/docs/asset_specs.md +++ b/docs/asset_specs.md @@ -1,37 +1,38 @@ # Asset types specs -| Type | Extension | Icon | ChipText | ChipColor | CanBeCreated | Category | HasThumbnail | CanBeEdited | EditorTool | -|----------------------|---------------|-------------------|----------|-----------|--------------|----------|--------------|-------------|---------------| -| Node | .tnode | Box | NODE | Red | false | | true | true | NodeEditor | -| Project Settings | .toast | Settings | SETTINGS | DeepPink | false | Project | false | true | GenericEditor | -| Material | .tmat | Eclipse | MAT | Green | true | Visual | false | true | GenericEditor | -| Material Instance | .tmi | Eclipse | INST | Green | true | Visual | false | true | GenericEditor | -| Shader | .slang | WandSparkles | SHADER | Green | true | Visual | false | false | | -| Mesh | .tmesh | Shapes | MESH | Blue | false | Visual | false | false | | -| Texture | .ktx2 | Image | TEX | Orange | false | Visual | true | false | | -| Voxel Model | .tvox | Boxes | VOX | Magenta | false | Visual | true | false | | -| Voxel Palette | .tpal | Brush | V PAL | Magenta | true | Visual | false | true | PaletteEditor | -| Animation | .tanim | Film | ANIM | Purple | false | Visual | false | false | | -| Physics Material | .tpm | Atom | PHYS | Orange | true | Physics | false | true | GenericEditor | -| Destruction Material | .tdm | Hammer | DSTY | Orange | true | Physics | false | true | GenericEditor | -| Input Action | .taction | Zap | ACTION | Yellow | true | Input | false | true | GenericEditor | -| Input Layout | .tlayout | Gamepad2 | LAYOUT | Yellow | true | Input | false | true | GenericEditor | -| Haptic Effect | .thaptic | Vibrate | HAPTIC | Yellow | true | Input | false | true | HapticsEditor | -| Script | .lua | CodeXml | LUA | Magenta | true | Logic | false | false | | -| Data | .toml | Database | DATA | Cyan | true | Data | false | true | GenericEditor | -| Schema | .schema.json | Settings | SCHEMA | Cyan | true | Data | false | true | SchemaEditor | -| Curve | .tcurve | Spline | CURVE | Cyan | true | Data | false | true | CurveEditor | -| Audio Bank | .bank | AudioWaveform | BANK | Beige | false | Audio | false | false | | -| Audio Strings | .strings.bank | BookHeadphones | BSTR | Beige | false | Audio | false | false | | -| Bus | .tbus | SlidersVertical | BUS | Beige | false | Audio | false | false | | -| VCA | .tvca | SlidersHorizontal | VCA | Beige | false | Audio | false | false | | -| Port | .taport | Speaker | PORT | Beige | false | Audio | false | false | | -| Snapshot | .tasnap | Activity | SNAP | Beige | false | Audio | false | false | | -| Audio Event | .tae | Volume2 | EVENT | Beige | false | Audio | false | false | | -| UI Element | .rml | AppWindow | UI | Blue | true | UI | false | false | | -| UI Style | .rcss | Brush | STYLE | Blue | true | UI | false | false | | -| UI Image | .tga | FileImage | IMG | Blue | false | UI | true | false | | -| Font | .ttf | Type | FONT | Blue | false | UI | false | false | | -| Localization | .tloc | Languages | LOC | Cyan | true | UI | false | true | TableEditor | -| Image Localization | .tiloc | Images | ILOC | Cyan | true | UI | false | true | TableEditor | -| Color Scheme | .tcolor | Palette | COLOR | Cyan | true | UI | false | true | GenericEditor | +| Type | Extension | Icon | ChipText | ChipColor | CanBeCreated | Category | HasThumbnail | CanBeEdited | EditorTool | +|----------------------|---------------|-------------------|----------|-----------|--------------|----------|--------------|-------------|---------------------| +| Node | .tnode | Box | NODE | Red | false | | true | true | NodeEditor | +| Project Settings | .toast | Settings | SETTINGS | DeepPink | false | Project | false | true | GenericEditor | +| Material | .tmat | Eclipse | MAT | Green | true | Visual | false | true | GenericEditor | +| Material Instance | .tmi | Eclipse | INST | Green | true | Visual | false | true | GenericEditor | +| Shader | .slang | WandSparkles | SHADER | Green | true | Visual | false | false | | +| Mesh | .tmesh | Shapes | MESH | Blue | false | Visual | false | false | | +| Texture | .ktx2 | Image | TEX | Orange | false | Visual | true | false | | +| Voxel Model | .tvox | Boxes | VOX | Magenta | false | Visual | true | false | | +| Voxel Palette | .tpal | Brush | V PAL | Magenta | true | Visual | false | true | PaletteEditor | +| Detail Texture | .tdet | Layers | DET | Orange | true | Visual | false | true | DetailTextureEditor | +| Animation | .tanim | Film | ANIM | Purple | false | Visual | false | false | | +| Physics Material | .tpm | Atom | PHYS | Orange | true | Physics | false | true | GenericEditor | +| Destruction Material | .tdm | Hammer | DSTY | Orange | true | Physics | false | true | GenericEditor | +| Input Action | .taction | Zap | ACTION | Yellow | true | Input | false | true | GenericEditor | +| Input Layout | .tlayout | Gamepad2 | LAYOUT | Yellow | true | Input | false | true | GenericEditor | +| Haptic Effect | .thaptic | Vibrate | HAPTIC | Yellow | true | Input | false | true | HapticsEditor | +| Script | .lua | CodeXml | LUA | Magenta | true | Logic | false | false | | +| Data | .toml | Database | DATA | Cyan | true | Data | false | true | GenericEditor | +| Schema | .schema.json | Settings | SCHEMA | Cyan | true | Data | false | true | SchemaEditor | +| Curve | .tcurve | Spline | CURVE | Cyan | true | Data | false | true | CurveEditor | +| Audio Bank | .bank | AudioWaveform | BANK | Beige | false | Audio | false | false | | +| Audio Strings | .strings.bank | BookHeadphones | BSTR | Beige | false | Audio | false | false | | +| Bus | .tbus | SlidersVertical | BUS | Beige | false | Audio | false | false | | +| VCA | .tvca | SlidersHorizontal | VCA | Beige | false | Audio | false | false | | +| Port | .taport | Speaker | PORT | Beige | false | Audio | false | false | | +| Snapshot | .tasnap | Activity | SNAP | Beige | false | Audio | false | false | | +| Audio Event | .tae | Volume2 | EVENT | Beige | false | Audio | false | false | | +| UI Element | .rml | AppWindow | UI | Blue | true | UI | false | false | | +| UI Style | .rcss | Brush | STYLE | Blue | true | UI | false | false | | +| UI Image | .tga | FileImage | IMG | Blue | false | UI | true | false | | +| Font | .ttf | Type | FONT | Blue | false | UI | false | false | | +| Localization | .tloc | Languages | LOC | Cyan | true | UI | false | true | TableEditor | +| Image Localization | .tiloc | Images | ILOC | Cyan | true | UI | false | true | TableEditor | +| Color Scheme | .tcolor | Palette | COLOR | Cyan | true | UI | false | true | GenericEditor | diff --git a/editor/Assets/DetailTextureFile.cs b/editor/Assets/DetailTextureFile.cs new file mode 100644 index 000000000..9cd80fcba --- /dev/null +++ b/editor/Assets/DetailTextureFile.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Tomlyn; +using Tomlyn.Model; + +namespace editor.Assets; + +public sealed class DetailTextureEntry { + public int Id { get; set; } + public string Name { get; set; } = ""; + public string AlbedoUid { get; set; } = ""; + public string RoughnessUid { get; set; } = ""; + public string HeightUid { get; set; } = ""; + public DetailTextureEntry Clone() => new() { Id = Id, Name = Name, AlbedoUid = AlbedoUid, RoughnessUid = RoughnessUid, HeightUid = HeightUid }; +} + +public sealed class DetailTextureFile { + public const int MaxTextures = 255; + public List Entries { get; } = []; + + public static DetailTextureFile FromFile(string path) => FromString(File.ReadAllText(path)); + + public static DetailTextureFile FromString(string toml) { + var table = TomlSerializer.Deserialize(toml) + ?? throw new FormatException("Detail texture: failed to parse TOML"); + + var file = new DetailTextureFile(); + if (!table.TryGetValue("textures", out var list) || list is not TomlTableArray entries) return file; + + var seen = new HashSet(); + foreach (var entry in entries) { + var id = entry.TryGetValue("id", out var v) ? v switch { long l => (int)l, int i => i, _ => 0 } : 0; + if (id is < 1 or > MaxTextures || !seen.Add(id)) continue; + + file.Entries.Add(new DetailTextureEntry { + Id = id, + Name = entry.TryGetValue("name", out var name) && name is string n ? n : "", + AlbedoUid = entry.TryGetValue("albedo", out var albedo) && albedo is string a ? a : "", + RoughnessUid = entry.TryGetValue("roughness", out var roughness) && roughness is string r ? r : "", + HeightUid = entry.TryGetValue("height", out var height) && height is string h ? h : "" + }); + } + + return file; + } + + public int NextFreeId() { + var used = Entries.Select(e => e.Id).ToHashSet(); + for (var id = 1; id <= MaxTextures; id++) + if (!used.Contains(id)) return id; + return 0; + } + + public string Serialize() { + var list = new TomlTableArray(); + foreach (var entry in Entries) { + var table = new TomlTable { + ["id"] = (long)Math.Clamp(entry.Id, 1, MaxTextures), + ["name"] = entry.Name + }; + if (entry.AlbedoUid.Length > 0) table["albedo"] = entry.AlbedoUid; + if (entry.RoughnessUid.Length > 0) table["roughness"] = entry.RoughnessUid; + if (entry.HeightUid.Length > 0) table["height"] = entry.HeightUid; + list.Add(table); + } + + return TomlSerializer.Serialize(new TomlTable { ["textures"] = list }); + } + + public void Save(string path) => File.WriteAllText(path, Serialize()); +} diff --git a/editor/Assets/Types/DetailTextureAsset.cs b/editor/Assets/Types/DetailTextureAsset.cs new file mode 100644 index 000000000..e3b1119ef --- /dev/null +++ b/editor/Assets/Types/DetailTextureAsset.cs @@ -0,0 +1,27 @@ +using System.IO; +using System.Threading.Tasks; +using Lucide.Avalonia; + +namespace editor.Assets.Types; + +public sealed class DetailTextureAsset : BaseAsset { + public override string Type => "detail_texture"; + public override string Extension => ".tdet"; + public override string DisplayName => "Detail Texture"; + public override string ChipText => "DET"; + public override string ChipColor => "Orange"; + public override LucideIconKind Icon => LucideIconKind.Layers; + public override bool CanBeCreated => true; + public override string Category => "Visual"; + public override bool HasThumbnail => false; + public override bool CanBeEdited => true; + + public override string EditorTool => "DetailTextureEditor"; + + public override string SchemaPath => ""; + + public override Task CreateAsync(string path) { + File.WriteAllText(path, "# Toast Detail Texture\n"); + return Task.CompletedTask; + } +} diff --git a/editor/Assets/VoxelPaletteFile.cs b/editor/Assets/VoxelPaletteFile.cs index 58b7671ad..2bef01d83 100644 --- a/editor/Assets/VoxelPaletteFile.cs +++ b/editor/Assets/VoxelPaletteFile.cs @@ -42,8 +42,10 @@ public sealed class VoxelPaletteEntry { public int TransformsTo { get; set; } - /// Layer of the detail library, 0 for none - public int DetailLayer { get; set; } + public int DetailId { get; set; } + public byte DetailTintR { get; set; } = 255; + public byte DetailTintG { get; set; } = 255; + public byte DetailTintB { get; set; } = 255; /// Texels per voxel edge, 0 for the engine default public int DetailScale { get; set; } @@ -52,6 +54,8 @@ public sealed class VoxelPaletteEntry { public float DetailRoughness { get; set; } public float DetailBump { get; set; } + public bool HasDetail => DetailId != 0; + public void CopyFrom(VoxelPaletteEntry other) { InUse = other.InUse; R = other.R; @@ -66,6 +70,14 @@ public void CopyFrom(VoxelPaletteEntry other) { Material = other.Material; HasMaterial = other.HasMaterial; TransformsTo = other.TransformsTo; + DetailId = other.DetailId; + DetailTintR = other.DetailTintR; + DetailTintG = other.DetailTintG; + DetailTintB = other.DetailTintB; + DetailScale = other.DetailScale; + DetailAlbedo = other.DetailAlbedo; + DetailRoughness = other.DetailRoughness; + DetailBump = other.DetailBump; } public void Clear() { @@ -77,7 +89,9 @@ public void Clear() { Alpha = 1f; Ior = DefaultIor; TransformsTo = 0; - DetailLayer = DetailScale = 0; + DetailId = 0; + DetailTintR = DetailTintG = DetailTintB = 255; + DetailScale = 0; DetailAlbedo = DetailRoughness = DetailBump = 0f; } } @@ -184,7 +198,12 @@ public static VoxelPaletteFile FromString(string toml) { target.TransformsTo = GetInt(entry, "transforms_to", 0); - target.DetailLayer = GetInt(entry, "detail_layer", 0); + target.DetailId = Math.Clamp(GetInt(entry, "detail_id", 0), 0, 255); + if (entry.TryGetValue("detail_tint", out var tint) && tint is TomlArray tintRgb && tintRgb.Count == 3) { + target.DetailTintR = ToByte(tintRgb[0]); + target.DetailTintG = ToByte(tintRgb[1]); + target.DetailTintB = ToByte(tintRgb[2]); + } target.DetailScale = GetInt(entry, "detail_scale", 0); target.DetailAlbedo = GetFloat(entry, "detail_albedo", 0f); target.DetailRoughness = GetFloat(entry, "detail_roughness", 0f); @@ -246,8 +265,11 @@ public string Serialize() { table["ior"] = Math.Round((double)Math.Clamp(entry.Ior, 1f, VoxelPaletteEntry.MaxIor), 2); if (entry.HasMaterial) table["material"] = (long)Math.Clamp(entry.Material, 0, SlotCount - 1); table["transforms_to"] = (long)Math.Clamp(entry.TransformsTo, 0, 255); - if (entry.DetailLayer != 0) { - table["detail_layer"] = (long)Math.Clamp(entry.DetailLayer, 0, 255); + if (entry.HasDetail) { + table["detail_id"] = (long)Math.Clamp(entry.DetailId, 0, 255); + table["detail_tint"] = new TomlArray { + (long)entry.DetailTintR, (long)entry.DetailTintG, (long)entry.DetailTintB + }; table["detail_scale"] = (long)Math.Clamp(entry.DetailScale, 0, 255); table["detail_albedo"] = (double)Clamp01(entry.DetailAlbedo); table["detail_roughness"] = (double)Clamp01(entry.DetailRoughness); diff --git a/editor/DetailTextureEditor/DetailTextureEditorView.axaml b/editor/DetailTextureEditor/DetailTextureEditorView.axaml new file mode 100644 index 000000000..ce9f53e59 --- /dev/null +++ b/editor/DetailTextureEditor/DetailTextureEditorView.axaml @@ -0,0 +1,283 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/editor/DetailTextureEditor/DetailTextureEditorView.axaml.cs b/editor/DetailTextureEditor/DetailTextureEditorView.axaml.cs new file mode 100644 index 000000000..9ab1e5edd --- /dev/null +++ b/editor/DetailTextureEditor/DetailTextureEditorView.axaml.cs @@ -0,0 +1,28 @@ +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using editor.Workspace; + +namespace editor.DetailTextureEditor; + +public partial class DetailTextureEditorView : UserControl { + public DetailTextureEditorView() { + InitializeComponent(); + AddHandler(PointerPressedEvent, (_, _) => (DataContext as DetailTextureEditorViewModel)?.EnsureEngine(), + RoutingStrategies.Tunnel, true); + AddHandler(KeyDownEvent, OnShortcut, RoutingStrategies.Tunnel, true); + } + + private void OnRowPressed(object? sender, PointerPressedEventArgs e) { + if (sender is Control { DataContext: DetailEntryVM item } && DataContext is DetailTextureEditorViewModel vm) + vm.SelectedItem = item; + } + + private void OnShortcut(object? sender, KeyEventArgs e) { + if (DataContext is not DetailTextureEditorViewModel vm || e.Source is TextBox || Viewport.IsEditorFlying) return; + if (e.Key == Key.S && e.KeyModifiers == KeyModifiers.Control) { + vm.SaveCommand.Execute(null); + e.Handled = true; + } + } +} diff --git a/editor/DetailTextureEditor/DetailTextureEditorViewModel.cs b/editor/DetailTextureEditor/DetailTextureEditorViewModel.cs new file mode 100644 index 000000000..d6e6649ce --- /dev/null +++ b/editor/DetailTextureEditor/DetailTextureEditorViewModel.cs @@ -0,0 +1,317 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using editor.Assets; +using editor.Engine; +using editor.Git; +using editor.Workspace; +using Proto.Events; + +namespace editor.DetailTextureEditor; + +public partial class DetailEntryVM : ObservableObject { + private readonly Action m_changed; + private bool m_loading = true; + + [ObservableProperty] private string m_name; + [ObservableProperty] private string? m_albedoUid; + [ObservableProperty] private string? m_roughnessUid; + [ObservableProperty] private string? m_heightUid; + [ObservableProperty] private bool m_isSelected; + + public DetailEntryVM(DetailTextureEntry entry, Action changed) { + Id = entry.Id; + m_name = entry.Name; + m_albedoUid = entry.AlbedoUid.Length > 0 ? entry.AlbedoUid : null; + m_roughnessUid = entry.RoughnessUid.Length > 0 ? entry.RoughnessUid : null; + m_heightUid = entry.HeightUid.Length > 0 ? entry.HeightUid : null; + m_changed = changed; + m_loading = false; + } + + public int Id { get; } + + public string Label => string.IsNullOrWhiteSpace(Name) ? $"{Id}:" : $"{Id}: {Name}"; + + partial void OnNameChanged(string value) { + OnPropertyChanged(nameof(Label)); + if (!m_loading) m_changed(); + } + + partial void OnAlbedoUidChanged(string? value) { + if (!m_loading) m_changed(); + } + + partial void OnRoughnessUidChanged(string? value) { + if (!m_loading) m_changed(); + } + + partial void OnHeightUidChanged(string? value) { + if (!m_loading) m_changed(); + } + + public DetailTextureEntry ToEntry() => new() { + Id = Id, Name = Name ?? "", AlbedoUid = AlbedoUid ?? "", RoughnessUid = RoughnessUid ?? "", HeightUid = HeightUid ?? "" + }; +} + +public partial class DetailTextureEditorViewModel : ObservableObject, IDisposable { + public const string PreviewPaletteUid = "DetailPrevA"; + public const string DrawBoxScript = "core://voxel_scripts/draw_box.lua"; + private const int PlaneVoxels = 96; + + private readonly DispatcherTimer m_previewTimer; + private bool m_disposed; + private bool m_sceneBuilt; + private bool m_loading; + private DetailTextureFile m_file = new(); + + [ObservableProperty] private bool m_isDirty; + [ObservableProperty] private DetailEntryVM? m_selectedItem; + + [ObservableProperty] private float m_albedo = 1f; + [ObservableProperty] private float m_tintR = 1f; + [ObservableProperty] private float m_tintG = 1f; + [ObservableProperty] private float m_tintB = 1f; + [ObservableProperty] private float m_roughness = 0.5f; + [ObservableProperty] private float m_bump = 0.5f; + + public DetailTextureEditorViewModel(WorkspaceViewModel workspace, string uid, string virtualPath) { + Workspace = workspace; + Uid = uid; + VirtualPath = virtualPath; + + Hierarchy = new HierarchyViewModel(() => Workspace) { Id = "DetailTextureHierarchy", Title = "Preview" }; + Hierarchy.HierarchyChanged += OnHierarchyChanged; + + Hierarchy.SelectedChanged += item => { + if (item is not null) Hierarchy.SelectedNode = null; + }; + + m_previewTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(150) }; + m_previewTimer.Tick += (_, _) => { + m_previewTimer.Stop(); + PushPreview(); + }; + + Load(); + } + + public WorkspaceViewModel Workspace { get; } + public HierarchyViewModel Hierarchy { get; } + public string Uid { get; } + public string VirtualPath { get; } + + public ObservableCollection Items { get; } = []; + + public string Title => $"Detail Texture - {Path.GetFileNameWithoutExtension(VirtualPath)}{(IsDirty ? " *" : "")}"; + + public bool HasSelection => SelectedItem is not null; + + private bool OwnsEngine => ViewportFocus.DetachedOwner == Workspace.EffectiveHandle && !m_disposed; + + private string RealPath => ProjectContext.Resolve(VirtualPath); + + private void Load() { + m_loading = true; + try { + m_file = DetailTextureFile.FromFile(RealPath); + } catch (Exception e) { + Log.Error($"Detail Texture Editor: failed to open '{VirtualPath}': {e.Message}"); + m_file = new DetailTextureFile(); + } + + Items.Clear(); + foreach (var entry in m_file.Entries) Items.Add(new DetailEntryVM(entry, OnEntryChanged)); + SelectedItem = Items.FirstOrDefault(); + IsDirty = false; + m_loading = false; + } + + private void OnEntryChanged() { + MarkDirty(); + } + + private void MarkDirty() { + if (m_loading) return; + IsDirty = true; + SchedulePreview(); + } + + partial void OnIsDirtyChanged(bool value) => OnPropertyChanged(nameof(Title)); + + partial void OnSelectedItemChanged(DetailEntryVM? oldValue, DetailEntryVM? newValue) { + if (oldValue is not null) oldValue.IsSelected = false; + if (newValue is not null) newValue.IsSelected = true; + } + + partial void OnSelectedItemChanged(DetailEntryVM? value) { + OnPropertyChanged(nameof(HasSelection)); + SchedulePreview(); + } + + partial void OnAlbedoChanged(float value) => SchedulePreview(); + partial void OnTintRChanged(float value) => SchedulePreview(); + partial void OnTintGChanged(float value) => SchedulePreview(); + partial void OnTintBChanged(float value) => SchedulePreview(); + partial void OnRoughnessChanged(float value) => SchedulePreview(); + partial void OnBumpChanged(float value) => SchedulePreview(); + + private void SchedulePreview() { + if (m_loading || m_disposed) return; + m_previewTimer.Stop(); + m_previewTimer.Start(); + } + + public void EnsureEngine() { + if (!OwnsEngine && !m_disposed) TakeEngine(); + } + + public void TakeEngine() { + if (m_disposed) return; + ViewportFocus.DetachedOwner = Workspace.EffectiveHandle; + Hierarchy.MakeCurrent(); + Events.Send(new SetActiveWorkspace { Handle = Workspace.EffectiveHandle }); + Events.Send(new RequestHierarchyUpdate()); + PushPreview(); + } + + private void OnHierarchyChanged() { + if (m_sceneBuilt || m_disposed || !OwnsEngine) return; + if (Workspace.RootUid is not { } root) return; + m_sceneBuilt = true; + + var script = MetaFile.ReadHeader(ProjectContext.Resolve(DrawBoxScript))?.Uid ?? ""; + Events.Send(new VoxelCreatePiece { + Parent = root, + Type = "toast::FillVolume", + Min = new VoxelInt3 { X = -PlaneVoxels / 2, Y = -PlaneVoxels / 2, Z = 0 }, + Max = new VoxelInt3 { X = (PlaneVoxels / 2) - 1, Y = (PlaneVoxels / 2) - 1, Z = 0 }, + Script = script, + Mode = 0 + }); + Events.Send(new NodeChangeParam { Node = root, Parameter = "m_palette", Value = PreviewPaletteUid }); + Workspace.SetEditorCameraModeCommand.Execute("Orbit"); + PushPreview(); + } + + private void PushPreview() { + if (!OwnsEngine) return; + Events.Send(new SetDetailTexturePreview { Uid = Uid }); + Events.Send(new PreviewAssetToml { Uid = Uid, Toml = CurrentFile().Serialize() }); + Events.Send(new PreviewAssetToml { Uid = PreviewPaletteUid, Toml = BuildPaletteToml() }); + } + + private DetailTextureFile CurrentFile() { + var file = new DetailTextureFile(); + file.Entries.AddRange(Items.Select(item => item.ToEntry())); + return file; + } + + private string BuildPaletteToml() { + var id = SelectedItem?.Id ?? 0; + static string Byte(float v) => ((int)Math.Round(Math.Clamp(v, 0f, 1f) * 255f)).ToString(CultureInfo.InvariantCulture); + static string Unit(float v) => Math.Clamp(v, 0f, 1f).ToString("0.###", CultureInfo.InvariantCulture); + + return "max_emissive = 1.0\n\n[[entries]]\nindex = 1\nmaterial = 0\n" + + "albedo = [200, 200, 200]\n" + + "roughness = 0.5\nmetallic = 0\n" + + $"detail_id = {id}\n" + + $"detail_tint = [{Byte(TintR)}, {Byte(TintG)}, {Byte(TintB)}]\n" + + $"detail_scale = 4\ndetail_albedo = {Unit(Albedo)}\ndetail_roughness = {Unit(Roughness)}\ndetail_bump = {Unit(Bump)}\n"; + } + + [RelayCommand] + private void AddTexture() { + var id = m_file.NextFreeId(); + if (id == 0) { + Log.Warn("Detail Texture Editor: all 255 ids are used"); + return; + } + + var used = Items.Select(i => i.Id).ToHashSet(); + while (used.Contains(id)) id++; + if (id > DetailTextureFile.MaxTextures) return; + + var item = new DetailEntryVM(new DetailTextureEntry { Id = id, Name = $"Texture {id}" }, OnEntryChanged); + Items.Add(item); + SelectedItem = item; + MarkDirty(); + } + + [RelayCommand] + private void DeleteSelected() { + if (SelectedItem is not { } item) return; + var index = Items.IndexOf(item); + Items.Remove(item); + SelectedItem = Items.Count == 0 ? null : Items[Math.Min(index, Items.Count - 1)]; + MarkDirty(); + } + + [RelayCommand] + private void MoveUp() => Move(-1); + + [RelayCommand] + private void MoveDown() => Move(1); + + private void Move(int delta) { + if (SelectedItem is not { } item) return; + var from = Items.IndexOf(item); + var to = from + delta; + if (to < 0 || to >= Items.Count) return; + Items.Move(from, to); + SelectedItem = item; + MarkDirty(); + } + + [RelayCommand] + private async Task Save() { + var file = CurrentFile(); + if (await GitLockGuard.SaveAsync(Uid, VirtualPath, path => Task.Run(() => file.Save(path)), (_, _) => Load())) { + IsDirty = false; + m_file = file; + } + } + + public async Task ConfirmCloseAsync() { + if (!IsDirty) return true; + switch (await App.Modals.ShowSaveChanges(Path.GetFileName(VirtualPath))) { + case Components.Modals.SaveChangesResult.Save: + await Save(); + return !IsDirty; + case Components.Modals.SaveChangesResult.DontSave: + return true; + default: + return false; + } + } + + public void Dispose() { + if (m_disposed) return; + m_previewTimer.Stop(); + if (OwnsEngine) { + try { + Events.Send(new PreviewAssetToml { Uid = Uid, Toml = File.ReadAllText(RealPath) }); + } catch (Exception e) { + Log.Warn($"Detail Texture Editor: could not restore '{VirtualPath}': {e.Message}"); + } + Events.Send(new SetDetailTexturePreview { Uid = "" }); + } + + m_disposed = true; + Hierarchy.HierarchyChanged -= OnHierarchyChanged; + Hierarchy.Dispose(); + if (ViewportFocus.DetachedOwner == Workspace.EffectiveHandle) ViewportFocus.DetachedOwner = 0; + Events.Send(new SetFocusedNode { Node = "" }); + Events.Send(new WorkspaceDestroy { Handle = Workspace.Handle }); + Workspace.Dispose(); + GC.SuppressFinalize(this); + } +} diff --git a/editor/DetailTextureEditor/DetailTextureEditorWindow.cs b/editor/DetailTextureEditor/DetailTextureEditorWindow.cs new file mode 100644 index 000000000..5f469f46e --- /dev/null +++ b/editor/DetailTextureEditor/DetailTextureEditorWindow.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; +using Avalonia.Controls; +using editor.Assets; +using editor.Engine; +using editor.Workspace; + +namespace editor.DetailTextureEditor; + +public sealed class DetailTextureEditorWindow : Window { + private static readonly Dictionary s_open = new(); + + private readonly DetailTextureEditorViewModel m_vm; + private bool m_confirmedClose; + + private DetailTextureEditorWindow(DetailTextureEditorViewModel vm) { + m_vm = vm; + Title = vm.Title; + Width = 1400; + Height = 860; + MinWidth = 900; + MinHeight = 520; + WindowStartupLocation = WindowStartupLocation.CenterOwner; + DataContext = vm; + Content = new DetailTextureEditorView { DataContext = vm }; + + Activated += (_, _) => m_vm.TakeEngine(); + vm.PropertyChanged += (_, e) => { + if (e.PropertyName == nameof(DetailTextureEditorViewModel.Title)) Title = vm.Title; + }; + + // Unsaved changes ask first + Closing += async (_, e) => { + if (m_confirmedClose || !vm.IsDirty) return; + e.Cancel = true; + if (!await vm.ConfirmCloseAsync()) return; + m_confirmedClose = true; + Close(); + }; + Closed += (_, _) => { + s_open.Remove(m_vm.Uid); + m_vm.Dispose(); + MainWindowViewModel.Current?.ReclaimEngine(); + }; + } + + public static void Open(string uid) { + if (s_open.TryGetValue(uid, out var existing)) { + existing.Activate(); + return; + } + + if (MainWindowViewModel.Current is not { } main || main.Engine is not { } engine) return; + if (!AssetDatabase.TryResolve(uid, out var virtualPath, out _)) { + Log.Warn($"Detail Texture Editor: no asset with uid {uid}"); + return; + } + + var workspace = WorkspaceViewModel.CreateNew(engine, "toast::ProceduralVoxel"); + if (workspace is null) { + Log.Warn($"Detail Texture Editor: could not create a preview workspace for {virtualPath}"); + return; + } + + var window = new DetailTextureEditorWindow(new DetailTextureEditorViewModel(workspace, uid, virtualPath)); + s_open[uid] = window; + if (App.MainWindow is { } owner) window.Show(owner); + else window.Show(); + } +} diff --git a/editor/Editors/PaletteView.axaml b/editor/Editors/PaletteView.axaml index 70b8dd5d7..fe3e238e4 100644 --- a/editor/Editors/PaletteView.axaml +++ b/editor/Editors/PaletteView.axaml @@ -114,7 +114,36 @@ - + + +